You can use componentsSeparatedByCharactersInSet: to split the string, and NSCountedSet will read the words for you.
1) Divide the line into words using a combination of punctuation, spaces and newlines:
NSMutableCharacterSet *separators = [NSMutableCharacterSet punctuationCharacterSet]; [separators formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSArray *words = [myString componentsSeparatedByCharactersInSet:separators];
2) Count the occurrences of words (if you want to ignore capital letters, you can do NSString *myString = [originalString lowercaseString]; before dividing the string into components):
NSCountedSet *frequencies = [NSCountedSet setWithArray:words]; NSUInteger aWordCount = [frequencies countForObject:@"word"]);
If you want to change your method signature, you can simply return the counted set.
source share