开发者

Manipulating strings in Objective-C

开发者 https://www.devze.com 2023-01-29 10:14 出处:网络
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? thanksYou need a mutable string, not a NSString.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消