如何在 NSString 中插入空格。
我需要在索引 5 处添加一个空格:
NString * dir = @"abcdefghijklmno";
要得到这个结果:
abcde fghijklmno
与:
NSLOG (@"%@", dir);
最佳答案
你需要使用NSMutableString
NSMutableString *mu = [NSMutableString stringWithString:dir];
[mu insertString:@" " atIndex:5];
或者你可以使用那些方法来拆分你的字符串:
– substringFromIndex:
– substringWithRange:
– substringToIndex:
然后用with重新组合它们
– stringByAppendingFormat:
– stringByAppendingString:
– stringByPaddingToLength:withString:startingAtIndex:
但是这种方式比它值得的麻烦更多。因为 NSString
是不可变的,所以你可以打赌很多对象的创建都是徒劳的。
NSString *s = @"abcdefghijklmnop";
NSMutableString *mu = [NSMutableString stringWithString:s];
[mu insertString:@" || " atIndex:5];
// This is one option
s = [mu copy];
//[(id)s insertString:@"er" atIndex:7]; This will crash your app because s is not mutable
// This is an other option
s = [NSString stringWithString:mu];
// The Following code is not good
s = mu;
[mu replaceCharactersInRange:NSMakeRange(0, [mu length]) withString:@"Changed string!!!"];
NSLog(@" s == %@ : while mu == %@ ", s, mu);
// ----> Not good because the output is the following line
// s == Changed string!!! : while mu == Changed string!!!
这会导致难以调试的问题。
这就是为什么 @property
for string 通常被定义为 copy
的原因,所以如果你得到一个 NSMutableString
,通过复制你可以确定它不会因为其他一些意外代码而改变。
我更喜欢 s = [NSString stringWithString:mu];
因为你不会对复制可变对象和返回不可变对象(immutable对象)感到困惑。
关于objective-c - 如何将字符插入 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8722051/