繁体   English   中英

在Objective-C中操作字符串

[英]Manipulating strings in Objective-C

我有一个10个字符的NSString。 我需要添加一个破折号 - 在角色位置4和8.最有效的方法是什么? 谢谢

你需要一个可变的字符串,而不是一个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创建的,你拥有内存并负责在将来的某个时候发布它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM