如果你想要做的是从字符串条空间,可以考虑:
_foo2 = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// or whitespaceAndNewlineCharacterSet, if that fits your use case better
如果你想成为一个更具体一点,有:
_foo2 = [foo stringByReplacingOccurrencesOfString:@" " withString:@""];
还是要更紧密地遵循你在做什么的语义,有:
NSArray *fooArray = [foo componentsSeparatedByString:@" "];
_foo2 = [fooArray componentsJoinedByString:@""];
如果因为某些原因,你真的想通过它循环(?也许做每个单词的一些处理),有一对夫妇的方式做到这一点:
NSArray *fooArray = [foo componentsSeparatedByString:@" "];
_foo2 = [NSMutableString string];
for (int i = 0; i < fooArray.count; i++) {
[_foo2 appendString:[fooArray objectAtIndex:i]];
}
或者:
NSArray *fooArray = [foo componentsSeparatedByString:@" "];
_foo2 = @""; // equivalent to [NSString string]
for (int i = 0; i < fooArray.count; i++) {
_foo2 = [_foo2 stringByAppendingString:[fooArray objectAtIndex:i]];
}
(这甚至没有考虑快速枚举,也就是for..in
构造。)第一个循环可能更有效率,因为我想象重复附加到同一个NSMutableString比创建新的字符串和抛弃旧字符串便宜。
在这里使用NSMutableString有点多余:'stringbyAppendingString:'创建一个新的字符串,其参数附加到接收者的内容中,所以接收者是否可变是无关紧要的。更重要的是,使用'alloc'来创建它意味着它在循环的第一次迭代中被泄漏(除非你使用ARC,这还不是安全的假设)。除此之外,你根本不需要循环,这取决于@Niels试图完成什么。在评论中有太多的细节需要讨论;看完整故事的答案。 – rickster 2012-03-17 20:29:38
我发布了一个更详细的新问题。希望这会更容易理解:)新的问题是:通过xcode中的txt文档进行解析器 – 2012-03-17 22:01:18