Reputation: 85
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.
Upvotes: 0
Views: 185
Reputation: 4750
NSString *strComplete = @"Appleeeeeeeeeeeeeee Appleeeeeeeee Aplleeeeeeeeee";
NSString *stringToFind = @"e";
NSArray *arySearch = [strComplete componentsSeparatedByString:stringToFind];
int countTheOccurrences = [arySearch count] - 1;
Output :
countTheOccurrences --- 34
Upvotes: 0
Reputation: 7783
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.
Upvotes: 0
Reputation: 3404
i have different idea let's try...
NSString *string = @"appple";
int times = [[string componentsSeparatedByString:@"p"] count]-1;
NSLog(@"Counted times: %i", times);
Upvotes: 3