文字列を指定すると、その文字列に表示される各単語の数を取得する必要があります。そのために、文字列で配列に文字列を抽出して検索しましたが、文字列を直接検索する方が最適です。以下は、私が最初に問題を解決するために書いたコードです。私はよりよい解決策に関する提案をしています。iOS - 文字列内の単語の出現回数を調べる最も効率的な方法
NSMutableDictionary *sets = [[NSMutableDictionary alloc] init];
NSString *paragraph = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"text" ofType:@"txt"] encoding:NSUTF8StringEncoding error:NULL];
NSMutableArray *words = [[[paragraph lowercaseString] componentsSeparatedByString:@" "] mutableCopy];
while (words.count) {
NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
NSString *search = [words objectAtIndex:0];
for (unsigned i = 0; i < words.count; i++) {
if ([[words objectAtIndex:i] isEqualToString:search]) {
[indexSet addIndex:i];
}
}
[sets setObject:[NSNumber numberWithInt:indexSet.count] forKey:search];
[words removeObjectsAtIndexes:indexSet];
}
NSLog(@"%@", sets);
例:
文字列の開始:
を "これはテストですこれはテストだけです。"
結果:
- "これ" - 2
- "である" - 2
- "テスト" - - 2
- "のみ" "" 2
- - 1
メソッドは機能しますか?ドット記号に問題はありませんか?私はあなたが "テスト"を持っているべきだと思います。 「テスト」ではなく、 – Ricardo