给定一个字符串,我需要获取该字符串中出现的每个单词的计数。为此,我按单词将字符串提取到一个数组中,并以这种方式进行搜索,但我觉得直接搜索字符串更为理想。下面是我最初为解决问题而编写的代码。不过,我愿意就更好的解决方案提出建议。
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
- “a2
- “测试” - 2
- “只有1个