Concatenate strings in Objective C

Objective C Jul 02, 2020 Viewed 14 Comments 0

Here are several ways to connect multiple strings using Objective C.

stringByAppendingString

To concatenate two strings into a new string:

NSString *string1 = @"This is";
NSString *string2 = @" a test.";
NSString *string3 = [string1 stringByAppendingString:string2];
// string3 is now @"This is a test."  string1 and string2 are unchanged.

You can also assign the new string back to string1:

NSString *string1 = @"This is";
NSString *string2 = @" a test.";
string1 = [string1 stringByAppendingString:string2];
// string1 is now @"This is a test."

NSMutableString

If you're using a NSMutableString, you can simply call the appendString method:

NSMutableString *string1 = [NSMutableString stringWithString:@"This is"];
NSString *string2 = @" a test.";
[string1 appendString:string2];
NSLog(@"string1: %@", string1);         // string1 现在是 @"This is a test."

NSArray

With NSArray, and call componentsJoinedByString to connect multiple strings together.

NSArray *arr = @[@"This", @"is", @"a", @"test"];
NSString *string = [arr componentsJoinedByString:@" "];
NSLog(@"%@", string);   // This is a test
Updated Jul 02, 2020