【发布时间】:2010-12-05 10:19:16
【问题描述】:
我有一个 10 个字符的 NSString。我需要在字符位置 4 和 8 添加破折号。最有效的方法是什么?谢谢
【问题讨论】:
标签: iphone objective-c cocoa-touch nsstring
我有一个 10 个字符的 NSString。我需要在字符位置 4 和 8 添加破折号。最有效的方法是什么?谢谢
【问题讨论】:
标签: iphone objective-c cocoa-touch nsstring
你需要一个可变字符串,而不是 NSString。
NSMutableString *str = [NSMutableString stringWithString:old_string];
[str insertString:@"-" atIndex:8];
[str insertString:@"-" atIndex:4];
基于stko 的回答修复了代码,没有错误。
【讨论】:
您应该注意首先在最高索引处插入破折号。如果您首先在索引 4 处插入,则需要在索引 9 处而不是 8 处插入第二个破折号。
例如这不会产生所需的字符串...
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 *newString = [originalString mutableCopy];
[newString insertString:@"-" atIndex:8];
[newString insertString:@"-" atIndex:4];
由于您使用的是 iPhone - 请务必注意,由于 newString 是使用 mutableCopy 创建的,因此您拥有内存并负责在未来某个时间释放它。
【讨论】: