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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/589395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:24:00  来源:igfitidea点击:

How to concatenate two strings on iPhone?

iphonestring

提问by Chilly Zhong

How to connect string "Hello" and string "World" to "HelloWorld"? Looks like "+" doesn't work.

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

回答by Garrett

NSString *string = [NSString stringWithFormat:@"%@%@", @"Hello", @"World"];
NSLog(@"%@", string);

That should do the trick, although I am sure there is a better way to do this, just out of memory. I also must say this is untestedso forgive me. Best thing is to find the stringWithFormat documentation for NSString.

这应该可以解决问题,尽管我确信有更好的方法可以做到这一点,只是内存不足。我还必须说这是未经测试的,所以请原谅我。最好的办法是找到 NSString 的 stringWithFormat 文档。

回答by Christopher

How about:

怎么样:

NSString *hello = @"Hello";
NSString *world = @"World";
NSString *helloWorld = [hello stringByAppendingString:world];

回答by Bill Heyman

If you have two literal strings, you can simply code:

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

NSString * myString = @"Hello" @"World";

This is a useful technique to break up long literal strings within your code.

这是在代码中分解长文本字符串的有用技术。

However, this will not work with string variables, where you'd want to use stringWithFormat: or stringByAppendingString:, as mentioned in the other responses.

但是,这不适用于字符串变量,您希望在其中使用 stringWithFormat: 或 stringByAppendingString:,如其他响应中所述。

回答by DaveJustDave

there's always NSMutableString..

总是有 NSMutableString ..

NSMutableString *myString = [NSMutableString stringWithString:@"Hello"];
[myString appendString: @"World"];

Note:

笔记:

NSMutableString *myString = @"Hello"; // won't work, literal strings aren't mutable

回答by raj

t3.text=[t1.text stringByAppendingString:t2.text];

回答by Ricardo Barroso

Bill, I like yout simple solution and I'd like to note that you can also eliminate the space between the two NSStrings:

比尔,我喜欢你简单的解决方案,我想指出你也可以消除两个 NSStrings 之间的空间:

NSString * myString = @"Hello"@"World";