How do I insert a space to a NSString.
I need to add a space at index 5 into:
NString * dir = @"abcdefghijklmno";
To get this result:
abcde fghijklmno
with:
NSLOG (@"%@", dir);
A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.
If you create an object using a method that begins with init, new, copy, or mutableCopy, then you own that object and are responsible for releasing it (or autoreleasing it) when you're done with it. If you create an object using any other method, that object is autoreleased, and you don't need to release it.
You need to use NSMutableString
NSMutableString *mu = [NSMutableString stringWithString:dir]; [mu insertString:@" " atIndex:5];
or you could use those method to split your string :
– substringFromIndex:
– substringWithRange:
– substringToIndex:
and recombine them after with
– stringByAppendingFormat:
– stringByAppendingString:
– stringByPaddingToLength:withString:startingAtIndex:
But that way is more trouble that it's worth. And since NSString
is immutable, you would bet lot of object creation for nothing.
NSString *s = @"abcdefghijklmnop"; NSMutableString *mu = [NSMutableString stringWithString:s]; [mu insertString:@" || " atIndex:5]; // This is one option s = [mu copy]; //[(id)s insertString:@"er" atIndex:7]; This will crash your app because s is not mutable // This is an other option s = [NSString stringWithString:mu]; // The Following code is not good s = mu; [mu replaceCharactersInRange:NSMakeRange(0, [mu length]) withString:@"Changed string!!!"]; NSLog(@" s == %@ : while mu == %@ ", s, mu); // ----> Not good because the output is the following line // s == Changed string!!! : while mu == Changed string!!!
Which can lead to difficult to debug problems. That is the reason why @property
for string are usually define as copy
so if you get a NSMutableString
, by making a copy you are sure it won't change because of some other unexpected code.
I tend to prefer s = [NSString stringWithString:mu];
because you don't get the confusion of copying a mutable object and having back an immutable one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With