文字列が与えられた場合、その文字列に表示される各単語の数を取得する必要があります。そのためには、文字列を単語ごとに配列に抽出して検索しましたが、文字列を直接検索する方が最適だと感じています。以下は、問題を解決するために私が最初に書いたコードです。しかし、私はより良い解決策についての提案を求めています。
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
- 「is」-2
- 「a」-2
- 「テスト」-2
- "たった1つ