提前抱歉这是一个初学者问题。以下是我正在尝试做的步骤:
无论出于何种原因,此代码会不断返回空匹配。我可以做什么?非常感谢您的帮助。
int main (int argc, const char * argv[])
{
@autoreleasepool {
// Place discrete words into arrays for respective lists
NSArray *regularwords = [[NSString stringWithContentsOfFile:@"/usr/dict/words" encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:@"\n"];
NSArray *propernames = [[NSString stringWithContentsOfFile:@"/usr/dict/propernames" encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:@"\n"];
// The compare and count loop
NSInteger *counter;
for (int i = 0; i < [propernames count]; i++) {
NSString *stringFromRegularWords = [regularwords objectAtIndex:i];
NSString *properNamesString = [propernames objectAtIndex:i];
if ([properNamesString isEqualToString:stringFromRegularWords]) {
counter++;
}
}
// Print the number of matches
NSLog(@"There was a total of %@ matching words", counter);
}
return 0;
}
答案 0 :(得分:2)
你正在做objectAtIndex:i
,希望两个文件中的单词完全相同。您应该做的是将其中一个文件中的条目添加到NSMutableSet,然后以这种方式检查成员资格。
// Place discrete words into arrays for respective lists
NSArray *regularwords = [[NSString stringWithContentsOfFile:@"/usr/dict/words" encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:@"\n"];
NSArray *propernames = [[NSString stringWithContentsOfFile:@"/usr/dict/propernames" encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:@"\n"];
// Add each of the words to a set so that we can quickly look them up
NSMutableSet* wordsLookup = [NSMutableSet set];
for (NSString* word in regularwords) {
[wordsLookup addObject:word];
}
NSInteger *counter;
for (NSString *properName in propernames) {
// This efficiently checks if the properName occurs in wordsLookup
if ([wordsLookup containsObject:properName]) {
counter++;
}
}
请注意,我的示例也使用“快速枚举”,即for ... in
语法。虽然没有必要解决您的问题,但它确实使代码更短并且可以说更快。