在一个单词中计算相同的字母

时间:2013-04-12 11:25:01

标签: iphone ios

我需要在一个单词中计算相同的字母。例如:苹果是我的话,我首先发现这封信中是否存在'a'。在那之后,我想计算那个词中'a'的数量,但我不能那样做。这是我的代码,它找到了特定的字母;

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

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


}

originalString是我从我的数据库中随机抽取的一个单词。那么,怎么算? 谢谢你的帮助。

3 个答案:

答案 0 :(得分:3)

我有不同的想法让我们试试......

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

    NSLog(@"Counted times: %i", times);

答案 1 :(得分:0)

您可以loop over the string once,将每个字母添加到NSMutableDictionary(作为键),并记录字母出现的次数(作为值)。

结果NSMutableDictionary将保存每个唯一字母的出现次数,从而可以提取您喜欢的内容。

答案 2 :(得分:0)

NSString *strComplete = @"Appleeeeeeeeeeeeeee Appleeeeeeeee Aplleeeeeeeeee";
NSString *stringToFind = @"e";
NSArray *arySearch = [strComplete componentsSeparatedByString:stringToFind];
int countTheOccurrences = [arySearch count] - 1;

输出

countTheOccurrences --- 34
相关问题