Iphone 在Objective-C中操作字符串

Iphone 在Objective-C中操作字符串,iphone,objective-c,cocoa-touch,nsstring,Iphone,Objective C,Cocoa Touch,Nsstring,我有一个10个字符的字符串。我需要在角色位置4和8添加一个破折号。最有效的方法是什么?谢谢您需要的是可变字符串,而不是NSString NSMutableString *str = [NSMutableString stringWithString:old_string]; [str insertString:@"-" atIndex:8]; [str insertString:@"-" atIndex:4]; NSMutableString *newString = [originalStr

我有一个10个字符的字符串。我需要在角色位置4和8添加一个破折号。最有效的方法是什么?谢谢

您需要的是可变字符串,而不是NSString

NSMutableString *str = [NSMutableString stringWithString:old_string];
[str insertString:@"-" atIndex:8];
[str insertString:@"-" atIndex:4];
NSMutableString *newString = [originalString mutableCopy];

[newString insertString:@"-" atIndex:8];
[newString insertString:@"-" atIndex:4];

修复了基于的答案的代码,该代码没有错误。

您应该注意首先在最高索引处插入破折号。如果先在索引4处插入,则第二个破折号将需要在索引9处插入,而不是在索引8处插入

e、 g.这不会产生所需的字符串

NSMutableString *s = [NSMutableString stringWithString:@"abcdefghij"];

[s insertString:@"-" atIndex:4];  // s is now @"abcd-efghij"
[s insertString:@"-" atIndex:8];  // s is now @"abcd-efg-hij"
而这一个是:

NSMutableString *s = [NSMutableString stringWithString:@"abcdefghij"];

[s insertString:@"-" atIndex:8];  // s is now @"abcdefgh-ij"
[s insertString:@"-" atIndex:4];  // s is now @"abcd-efgh-ij"

这里有一种稍微不同的方法,即获取原始NSString的可变副本

NSMutableString *str = [NSMutableString stringWithString:old_string];
[str insertString:@"-" atIndex:8];
[str insertString:@"-" atIndex:4];
NSMutableString *newString = [originalString mutableCopy];

[newString insertString:@"-" atIndex:8];
[newString insertString:@"-" atIndex:4];
由于您使用的是iPhone—需要注意的是,由于
newString
是使用
mutableCopy
创建的,因此您拥有内存,并负责在将来某个时候释放它