Let’s assume we have these strings:
NSString *firstString = @"This is the start"; NSString *secondString = @"of a great"; NSString *thirdString = @" sentence that ends here";
The easiest way to concatenate two strings is by using the stringByAppendingString: method.
NSString *concatenatedString = [firstString stringByAppendingString:secondString];
If you would like to concatenate 3 strings then it’s probably easier to construct a new string out of the three by using stringWithFormat: method
NSString *allThreeStrings = [NSString stringWithFormat:@"%@ %@ and boring %@", firstString, secondString, thirdString];
Or you could use NSMutableString like this:
NSMutableString *mutableString = [NSMutableString stringWithString:firstString]; [mutableString appendFormat:@"%@ %@", secondString, thirdString];
Or like this:
NSMutableString *anotherOne = [NSMutableString stringWithString:firstString]; [anotherOne appendString:secondString]; [anotherOne appendString:thirdString];
I found yet another way on Stack Overflow. For your example strings, if they don’t have a space at the beginning or end, you can also connect them like this:
NSArray *fields = @[firstString, secondString, thirdString];
NSString *outputString = [fields componentsJoinedByString:@” “];
Good find, thanks for sharing!