比较两个文件中的字符串在Objective C中返回Null

时间:2012-07-02 08:29:33

标签: objective-c nsstring nsarray

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

  1. 读取两个文本文件(unix单词列表文件以获取正确的名称和 常规词)
  2. 将文本分隔为字符串
  3. 将分隔的字符串放入每个列表的数组
  4. 比较数组并计算匹配数
  5. 无论出于何种原因,此代码会不断返回空匹配。我可以做什么?非常感谢您的帮助。

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

1 个答案:

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