給定一個字符串,我需要獲取出現在該字符串中的每個單詞的計數。爲此,我通過單詞將字符串提取到一個數組中,然後以這種方式進行搜索,但我有這樣的感覺,即直接搜索字符串更加優化。以下是我最初編寫的用於解決問題的代碼。儘管如此,我仍然希望獲得更好的解決方案。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