I have a NSString with 10 characters. I need to add a dash - at character position 4 and 8. What is the most efficient way to do this? thanks
You need a mutable string, not a NSString.
NSMutableString *str = [NSMutableString stringWithString:old_string];
[str insertString:@"-" atIndex:8];
[str insertString:@"-" atIndex:4];
Fixed code based on stko's answer, which is bug free.
You should take care to insert the dash at the highest index first. If you insert at index 4 first, you will need to insert at index 9 instead of 8 for the second dash.
e.g. This does not produce the desired string...
NSMutableString *s = [NSMutableString stringWithString:@"abcdefghij"];
[s insertString:@"-" atIndex:4]; // s is now @"abcd-efghij"
[s insertString:@"-" atIndex:8]; // s is now @"abcd-efg-hij"
While this one does:
NSMutableString *s = [NSMutableString stringWithString:@"abcdefghij"];
[s insertString:@"-" atIndex:8]; // s is now @"abcdefgh-ij"
[s insertString:@"-" atIndex:4]; // s is now @"abcd-efgh-ij"
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