添加到NSString

时间:2012-05-26 20:09:13

标签: iphone objective-c xcode

我有一个NSString,我想添加额外的字符。在我看来,我认为它会像这样简单:

NSString *answerString = [NSString stringWithFormat:@"%f", finalVolume] + @" Cubic Feet";

但那没用。有谁知道我在这里可能会缺少什么?谢谢!

7 个答案:

答案 0 :(得分:2)

NSString是不可变的,所以你不能只是添加它。相反,你要么像这样编写你的字符串:

NSString *answerString = [NSString stringWithFormat:@"%f Cubic Feet", finalVolume];

NSString *unit = @"Cubic Feet";
NSString *answerString = [NSString stringWithFormat:@"%f %@", finalVolume, unit];

或创建一个可变的:

NSMutableString *answerString = [NSMutableString stringWithFormat:@"%f ", finalVolume];
[answerString appendString:@"Cubic Feet"];

答案 1 :(得分:1)

使用NSMutableString

你可以附加任何你想要的东西......

答案 2 :(得分:1)

我很确定你可以做到以下几点:

NSString *answerString = [NSString stringWithFormat:@"%f Cubic Feet", finalVolume];

或者如果要追加的部分需要变量,您可以执行以下操作:

NSString *answerString = [NSString stringWithFormat:@"%f %@", finalVolume, myVariable];

答案 3 :(得分:1)

[[NSString stringWithFormat:@"%f", finalVolume] stringByAppendingString:@" Cubic Feet"];

答案 4 :(得分:1)

只需使用

NSString *answerString = [NSString stringWithFormat:@"%f %@", finalVolume,@"Cubic Feet"];

答案 5 :(得分:1)

NSMutableString *str = [[NSMutableString alloc] init];
[str appendString:@"s1"];
[str appendString:@"s2"];

答案 6 :(得分:1)

[NSString stringwithformat:@"%f %@", final value, @"cubic feet"];