objective-c - 如何将字符插入 NSString

标签 objective-c ios5 nsstring

如何在 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/

相关文章:

objective-c - 用负值更新 NSRect 大小

objective-c - 带有自定义后退导航按钮的自定义按钮栏

objective-c - 将十六进制字符串转换为长

ios - NSString sizeWithFont :forWidth:lineBreakMode: method (in the iPhone SDK)? 的文档

objective-c - 让这段代码更有效率?

iphone - 是否有 Emoji 字符的 Unicode 编码范围列表?

Objective-C:获取触发 UIEvent 的 UITouch

c++ - 如何在 ios 平台上使用 c++ 实现 GameCenter

iphone - 在 xCode 中对 Web 服务收费时出现重复的 MKAnnotations

iOS 4.3 Statusbar隐藏显示白条