我正在检查一个字符串是否在数组中连续出现两次。这段代码似乎不起作用,因为它只是打印出整个数组。我错过了什么?
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];
}
最佳答案
compare:
和相关函数不返回 bool 值,它们返回 NSComparisonResult
。如果您想查看字符串是否相等,您应该使用
if ([n compare:lastOne options:NSCaseInsensitiveSearch] == NSOrderedSame)
关于objective-c - 为什么 -[NSString 比较 :options:] return true when the strings are not equal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22442172/