brmcdani44
brmcdani44

Reputation: 27

Adding Onto NSString

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!

Upvotes: 0

Views: 89

Answers (7)

Shehzad Bilal
Shehzad Bilal

Reputation: 2523

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

Upvotes: 1

Alladinian
Alladinian

Reputation: 35616

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"];

Upvotes: 2

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

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

Upvotes: 1

Manlio
Manlio

Reputation: 10865

Simply use

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

Upvotes: 1

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

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

Upvotes: 1

Josh Mein
Josh Mein

Reputation: 28635

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

Upvotes: 1

iTukker
iTukker

Reputation: 2083

Use NSMutableString

You can append anything you like...

Upvotes: 1

Related Questions