Manipulating strings in Objective-C
I have a NSString with 10 characters. I need to add a d开发者_JS百科ash - 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"
Here's a slightly different way of doing this — which is to get a mutable copy of your original NSString.
NSMutableString *newString = [originalString mutableCopy];
[newString insertString:@"-" atIndex:8];
[newString insertString:@"-" atIndex:4];
Since you're on the iPhone - it's important to note that since the newString
is created with mutableCopy
you own the memory and are responsible for releasing it at some future point.
精彩评论