0

I need to count same letters in a word. For example: apple is my word and first I found whether 'a' exists in this letter or not. After that I want to count the number of 'a' in that word but I couldn't do that. This is my code which finds the specific letter;

if([originalString rangeOfString:compareString].location==NSNotFound)
{
    NSLog(@"Substring Not Found");
}

else
{
    NSLog(@"Substring Found Successfully");


}

originalString is a word which I took from my database randomly. So, how to count? Thanks for your help.

user1913674
  • 85
  • 1
  • 7
  • like when you found 'a' then you need to count a in you String ? please clear your Question – Buntylm Apr 12 '13 at 11:29
  • You could set an integer variable to keep track and increment it every time you get a match - e.g. something like: `int i = 0; if (![originalString rangeOfString:compareString].location==NSNotFound) i++;` – Robert Apr 12 '13 at 11:30
  • if you need the to know how many times the letter `a` is in the word apple you could use `regular expressions` try to match the letter a, and check the count of the matches. – 2pietjuh2 Apr 12 '13 at 11:35
  • Yes, I need to count a in my string – user1913674 Apr 12 '13 at 11:37

3 Answers3

3

i have different idea let's try...

  NSString *string = @"appple";
    int times = [[string componentsSeparatedByString:@"p"] count]-1;

    NSLog(@"Counted times: %i", times);
Arun
  • 3,406
  • 4
  • 30
  • 55
0

You could just loop over the string once, adding each letter to an NSMutableDictionary (as the key) and keeping a tally of how many times the letter occurs (as the value).

The resulting NSMutableDictionary would hold the number of occurences for each unique letter, whereby you can extract what you like.

Community
  • 1
  • 1
LeonardChallis
  • 7,759
  • 6
  • 45
  • 76
0
NSString *strComplete = @"Appleeeeeeeeeeeeeee Appleeeeeeeee Aplleeeeeeeeee";
NSString *stringToFind = @"e";
NSArray *arySearch = [strComplete componentsSeparatedByString:stringToFind];
int countTheOccurrences = [arySearch count] - 1;

Output :

countTheOccurrences --- 34
Manu
  • 4,730
  • 2
  • 20
  • 45