0

I have an NSString that I would like to add extra characters to. In my mind I thought it would be something simple like this:

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

But that did not work. Does anyone know what I might be missing here? Thanks!

4

7 回答 7

2

NSString is immutable, so you cannot just add to it. Instead, you either compose your string like this:

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

or

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

or create a mutable one:

NSMutableString *answerString = [NSMutableString stringWithFormat:@"%f ", finalVolume];
[answerString appendString:@"Cubic Feet"];
于 2012-05-26T20:14:44.893 回答
1

Use NSMutableString

You can append anything you like...

于 2012-05-26T20:12:09.860 回答
1

I am pretty sure you can do the following:

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

or if the part being appended needs to be variable you can do the following:

NSString *answerString = [NSString stringWithFormat:@"%f %@", finalVolume, myVariable];
于 2012-05-26T20:12:21.230 回答
1
[[NSString stringWithFormat:@"%f", finalVolume] stringByAppendingString:@" Cubic Feet"];
于 2012-05-26T20:12:35.067 回答
1

Simply use

NSString *answerString = [NSString stringWithFormat:@"%f %@", finalVolume,@"Cubic Feet"];
于 2012-05-26T20:13:14.477 回答
1
NSMutableString *str = [[NSMutableString alloc] init];
[str appendString:@"s1"];
[str appendString:@"s2"];
于 2012-05-26T20:13:39.393 回答
1
[NSString stringwithformat:@"%f %@", final value, @"cubic feet"];
于 2012-05-26T20:14:56.420 回答