lis*_*isa 2 iphone cocoa-touch objective-c nsstring
我有一个10个字符的NSString.我需要添加一个破折号 - 在角色位置4和8.最有效的方法是什么?谢谢
Der*_*ick 12
你需要一个可变的字符串,而不是NSString.
NSMutableString *str = [NSMutableString stringWithString:old_string];
[str insertString:@"-" atIndex:8];
[str insertString:@"-" atIndex:4];
Run Code Online (Sandbox Code Playgroud)
固定代码基于stko的答案,没有错误.
小智 6
您应该首先在最高索引处插入破折号.如果首先在索引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"
Run Code Online (Sandbox Code Playgroud)
虽然这个做了:
NSMutableString *s = [NSMutableString stringWithString:@"abcdefghij"];
[s insertString:@"-" atIndex:8]; // s is now @"abcdefgh-ij"
[s insertString:@"-" atIndex:4]; // s is now @"abcd-efgh-ij"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1083 次 |
| 最近记录: |