用变量追加字符串

时间:2011-08-15 19:58:09

标签: objective-c ios xcode nsstring nsmutablestring

我是一个来自Objective-C的java人。在java中,要将变量添加到字符串中,您必须执行以下操作:

someString = "This string is equal to " + someNumber + ".";

我无法弄清楚如何在Objective-C中做到这一点。我有一个NSMutableString,我想添加到字符串的中间。我该怎么做呢?

我试过了:

NSString *someText = @"Lorem ipsum " + someMutableString;
NSString *someText = @"Lorem ipsum " + [someMutableString stringForm];

以及其他一些事情,似乎都没有效果。同时将+, s互换。

4 个答案:

答案 0 :(得分:29)

您可以使用appendString:,但一般来说,我更喜欢:

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]];
等等......

这些字符串是自动释放的,因此请注意不要失去它们的价值。如有必要,请保留或复制它们,稍后自行释放。

答案 1 :(得分:9)

试试这个:

NSMutableString * string1 = [[NSMutableString alloc] initWithString:@"this is my string"];

[string1 appendString:@" with more strings attached"];

//release when done
[string1 release];

答案 2 :(得分:6)

您需要使用stringByAppendingString

NSString* string = [[NSString alloc] initWithString:@"some string"];
string = [string stringByAppendingString:@" Sweet!"];

当你完成任务时,不要忘记[string release];

答案 3 :(得分:0)

NSMutableString *string = [[NSMutableString alloc] init];

[string appendFormat:@"more text %@", object ];