0

これはこのような初心者の質問であるため、事前に申し訳ありません。これが私がやろうとしていることのステップです:

  1. 2つのテキストファイルを読み取ります(適切な名前と通常の単語のUNIX単語リストファイル)
  2. テキストを文字列に分割します
  3. 分離された文字列をリストごとに配列に配置します
  4. 配列を比較し、一致する数を数えます

何らかの理由で、このコードは継続的にnull一致を返します。私は何をしているのでしょうか?助けてくれてありがとう。

    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両方のファイルで単語がまったく同じインデックスにあることを期待して、実行しています。おそらく行うべきことは、ファイルの1つから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 に答える