如何将字符插入NSString

Joh*_*lla 34 objective-c nsstring ios5

如何向NSString插入空格.

我需要在索引5处添加一个空格:

NString * dir = @"abcdefghijklmno";
Run Code Online (Sandbox Code Playgroud)

要获得此结果:

abcde fghijklmno
Run Code Online (Sandbox Code Playgroud)

有:

NSLOG (@"%@", dir);
Run Code Online (Sandbox Code Playgroud)

Vin*_*ier 89

你需要使用 NSMutableString

NSMutableString *mu = [NSMutableString stringWithString:dir];
[mu insertString:@" " atIndex:5];
Run Code Online (Sandbox Code Playgroud)

或者您可以使用这些方法来拆分字符串:

- substringFromIndex:
- substringWithRange:
- substringToIndex:

然后重新组合它们

- 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!!! 
Run Code Online (Sandbox Code Playgroud)

这可能导致难以调试的问题.这就是为什么@property字符串通常copy如此定义的原因如果你得到一个NSMutableString,通过制作一个副本你肯定它不会因为一些其他意外的代码而改变.

我倾向于更喜欢,s = [NSString stringWithString:mu];因为你不会混淆复制一个可变对象并拥有一个不可变对象.