I want to place a string within a string. Basically in pseudo code:
"first part of string" + "(varying string)" + "third part of string" How can I do this in objective-c? Is there a way to easily concatenate in obj-c? Thanks!
Yes, do
NSString *str = [NSString stringWithFormat: @"first part %@ second part", varyingString]; For concatenation you can use stringByAppendingString
NSString *str = @"hello "; str = [str stringByAppendingString:@"world"]; //str is now "hello world" For multiple strings
NSString *varyingString1 = @"hello"; NSString *varyingString2 = @"world"; NSString *str = [NSString stringWithFormat: @"%@ %@", varyingString1, varyingString2]; //str is now "hello world" Variations on a theme:
NSString *varying = @"whatever it is"; NSString *final = [NSString stringWithFormat:@"first part %@ third part", varying]; NSString *varying = @"whatever it is"; NSString *final = [[@"first part" stringByAppendingString:varying] stringByAppendingString:@"second part"]; NSMutableString *final = [NSMutableString stringWithString:@"first part"]; [final appendFormat:@"%@ third part", varying]; NSMutableString *final = [NSMutableString stringWithString:@"first part"]; [final appendString:varying]; [final appendString:@"third part"]; You would normally use -stringWithFormat here.
NSString *myString = [NSString stringWithFormat:@"%@%@%@", @"some text", stringVariable, @"some more text"]; Iam amazed that none of the top answers pointed out that under recent Objective-C versions (after they added literals), you can concatenate just like this:
@"first" @"second" And it will result in:
@"firstsecond" You can not use it with NSString objects, only with literals, but it can be useful in some cases.
[NSString stringWithFormat:@"Just google '%@'!", @"http://www.google.hu/search?q=nsstring+class+reference&ie=UTF-8&oe=UTF-8&hl=en-gb&client=safari"];