我正在检查一个字符串是否在一个数组中连续出现两次。这段代码似乎不起作用,因为它只打印出整个数组。我错过了什么?
NSString *nameString =
[NSString stringWithContentsOfFile:@"/usr/share/dict/words"
encoding:NSUTF8StringEncoding
error:NULL];
NSArray *names = [nameString componentsSeparatedByString:@"\n"];
//Save last item
NSMutableString *lastOne = [NSMutableString stringWithCapacity:20];
// Go through the array one string at a time
for (NSString *n in names) {
if ([n compare:lastOne options:NSCaseInsensitiveSearch]) {
NSLog(@"%@", n);
}
[lastOne setString:n];
}
答案 0 :(得分:7)
compare:
及相关功能不会返回布尔值,他们返回NSComparisonResult
。如果你想看一个字符串是否相等,你应该使用
if ([n compare:lastOne options:NSCaseInsensitiveSearch] == NSOrderedSame)