문자열이 있으면 해당 문자열에 나타나는 각 단어의 수를 가져와야합니다. 그렇게하기 위해, 나는 문자열로 문자열을 문자열로 추출하고 그런 식으로 검색했지만, 문자열을 직접 검색하는 것이 더 최적이라고 생각했습니다. 아래는 내가 원래 문제를 해결하기 위해 작성한 코드입니다. 그래도 더 나은 솔루션에 대한 제안을하고 있습니다.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
- "A"- - 2
- "테스트"- 2
- "전용"2
- "입니다"- 1
방법은 작동합니까? 도트 기호에 문제가 있습니까? 나는 당신이 "시험"을해야한다고 생각합니다. "테스트"보다는. – Ricardo