我有一个NSString,我们说“你好”..。在每个字符之间用逗号填充此字符串的最快方法是什么?(包括第一个字符之前)
所以返回的字符串应该是,",H,E,L,L,O“
我只是想做一个for循环,并让一个变量在每次添加逗号时向上加2,这样它就会经过新的逗号和下一个字母,然后添加一个逗号,然后检查该变量除以2是否大于原始字符串的长度……有没有更好的方法?
发布于 2013-02-11 00:02:44
或者,您可以仅将字符附加到可变字符串:
NSString *original = @"Hello";
NSUInteger len = original.length;
NSMutableString *newStr = [NSMutableString stringWithCapacity:len * 2];
for (int i = 0; i < len; i++) {
[newStr appendFormat:@",%C", [original characterAtIndex:i]];
}发布于 2013-02-11 00:16:56
如果你喜欢正则表达式,你可以使用它们。不确定性能,因此对于长字符串,您可能需要验证这一点。
它的核心是两行代码:
NSString *orgString = @"Hello"; // Not part of the meat, for the line counters out there...
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"."
options:0
error:nil];
NSString *commaString = [regex stringByReplacingMatchesInString:orgString
options:0
range:NSMakeRange(0, orgString.length)
withTemplate: @",$0"];我没有检查正则表达式的错误,因为它只由一个点组成。这真的应该在操作系统的未来版本中进行编译。
https://stackoverflow.com/questions/14799559
复制相似问题