用变量追加字符串 [英] Append string with variable
问题描述
我是一个来自Objective-C的java人。在java中,要向字符串添加变量,您必须执行以下操作:
I'm a java guy coming over to Objective-C. In java, to add a variable to a string you'd have to do something along the lines of:
someString = "This string is equal to " + someNumber + ".";
我无法弄清楚如何在Objective-C中做到这一点。我有一个 NSMutableString
,我想添加到字符串的中间。我该怎么做呢?
I can't figure out how to do it in Objective-C though. I have an NSMutableString
that I'd like to add to the middle of a string. How do I go about doing this?
我试过:
NSString *someText = @"Lorem ipsum " + someMutableString;
NSString *someText = @"Lorem ipsum " + [someMutableString stringForm];
以及其他一些东西,其中任何一个似乎都不起作用。还用,
s互换 +
。
and a few other things, none of which seem to work. Also interchanged the +
s with ,
s.
推荐答案
你可以使用 appendString:
,但一般来说,我更喜欢:
You can use appendString:
, but in general, I prefer:
NSString *someText = [NSString stringWithFormat: @"Lorem ipsum %@", someMutableString];
NSString *someString = [NSString stringWithFormat: @"This is string is equal to %d.", someInt];
NSString *someOtherString = [NSString stringWithFormat: @"This is string is equal to %@.", someNSNumber];
或者:
NSString *someOtherString = [NSString stringWithFormat: @"This is string is equal to %d.", [someNSNumber intValue]];
等...
这些字符串是自动释放的,所以要注意不要失去它们的价值。如有必要,请保留或复制它们并稍后自行释放。
These strings are autoreleased, so take care not to lose their value. If necessary, retain or copy them and release them yourself later.
这篇关于用变量追加字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!