title: iOS - Most efficient way to find word occurrence count in a string
body: <p>Given a string, I need to obtain a count of each word that appears in that string. To do so, I extracted the string into an array, by word, and searched that way, but I have the feeling that searching the string directly is more optimal. Below is the code that I originally wrote to solve the problem. I'm up for suggestions on better solutions though.</p>
  
  <pre><code>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 &lt; 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);
  </code></pre>
  
  <p><strong>Example:</strong> </p>
  
  <p><em>Starting string:</em><br>
  "This is a test. This is only a test."</p>
  
  <p><em>Results:</em>  </p>
  
  <ul>
  <li>"This" - 2 </li>
  <li>"is"   - 2 </li>
  <li>"a"    - 2 </li>
  <li>"test" - 2 </li>
  <li>"only" - 1</li>
  </ul>