How to insert a character into a NSString

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.


And here, for example, is how to insert a space every 3 chars...

NSMutableString *mutableString = [NSMutableString new];
[mutableString setString:@"abcdefghijklmnop"];

for (int p = 0; p < [mutableString length]; p++) {
    if (p%4 == 0) {
        [mutableString insertString:@" " atIndex:p];
    }
}

NSLog(@"%@", mutableString);

result: abc def ghi jkl mno p