如何在iPhone上连接两个字符串?

Chi*_*ong 13 string iphone

如何将字符串"Hello"和字符串"World"连接到"HelloWorld"?看起来"+"不起作用.

Gar*_*ett 40

NSString *string = [NSString stringWithFormat:@"%@%@", @"Hello", @"World"];
NSLog(@"%@", string);
Run Code Online (Sandbox Code Playgroud)

这应该是诀窍,虽然我确信有更好的方法来做到这一点,只是内存不足.我也必须说这是未经测试的,请原谅我.最好的方法是找到NSString的stringWithFormat文档.


Chr*_*her 28

怎么样:

NSString *hello = @"Hello";
NSString *world = @"World";
NSString *helloWorld = [hello stringByAppendingString:world];
Run Code Online (Sandbox Code Playgroud)


小智 10

如果你有两个文字字符串,你可以简单地编码:

NSString * myString = @"Hello" @"World";
Run Code Online (Sandbox Code Playgroud)

这是一种在代码中分解长文字字符串的有用技巧.

但是,这不适用于字符串变量,您需要使用stringWithFormat:或stringByAppendingString:,如其他响应中所述.


Dav*_*ave 5

总有NSMutableString ..

NSMutableString *myString = [NSMutableString stringWithString:@"Hello"];
[myString appendString: @"World"];
Run Code Online (Sandbox Code Playgroud)

注意:

NSMutableString *myString = @"Hello"; // won't work, literal strings aren't mutable
Run Code Online (Sandbox Code Playgroud)