Nikita Jerschow
Nikita Jerschow

Reputation: 866

How do I add a character to an already existing string?

When I make:

NSString x = @"test"

How do I edit it so that it becomes "testing"?

And when I put:

NSMutableString x = [[NSMutableString alloc] initWithString:@"test"];

There is an error that says:

Initializer element is not a compile-time constant.

Thanks

Upvotes: 2

Views: 222

Answers (3)

Kaz
Kaz

Reputation: 1466

if you want to add multiple or single strings to an existing NSString use the following

NSString *x =  [NSString stringWithFormat:@"%@%@", @"test",@"ing"];

Upvotes: 2

Mark Granoff
Mark Granoff

Reputation: 16938

You need to declare your NSString or NSMutableString as *x. These are pointers to objects.

To change a string in code is quite easy, for example:

NSString *test = @"Test";
test = [test stringByAppendingString:@"ing"];

And the value in test will now be Testing.

There are a lot of great NSString methods, both instance and class methods, for manipulating and working with strings. Check the documentation for the complete list!

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

When declaring NSMutableString, you missed the asterisk:

NSMutableString *x = [[NSMutableString alloc] initWithString:@"test"];
// Here --------^

With a mutable string in hand, you can do

[x appendString:@"ing"];

to make x equal testing.

You do not have to go through a mutable string - this will also work:

NSString *testing = [NSString stringWithFormat:@"%@ing", test];

Upvotes: 8

Related Questions