How do I add a character to an already existing string?
-
08-07-2021 - |
Question
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
La solution
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];
Autres conseils
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!
if you want to add multiple or single strings to an existing NSString use the following
NSString *x = [NSString stringWithFormat:@"%@%@", @"test",@"ing"];