0

提前抱歉,这是一个初学者的问题。以下是我正在尝试做的步骤:

  1. 读取两个文本文件(用于专有名称和常规单词的 unix 单词列表文件)
  2. 将文本分成字符串
  3. 将分隔的字符串放入每个列表的数组中
  4. 比较数组并计算匹配数

无论出于何种原因,此代码都会不断返回空匹配项。我可能在做什么?非常感谢您的帮助。

    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;
}
4

1 回答 1

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语法。虽然没有必要解决您的问题,但它确实使代码更短并且可以说更快。

于 2012-07-02T08:32:10.693 回答