c++ - 在 char 数组中查找出现次数最多的字符

标签 c++ string char

我正在尝试使用以下算法在此数组中找到出现次数最多的字符:

char a[]={"aaaadddddaa"};
int max=0;
int count=0;
char maxCharcter;
for(char q='a';q<='z';q++)
{
    for(int i=0; i<strlen(a);i++)
    {
        if(a[i]==q)
            count++;
    }

    if(count>max)
    {
        max=count;
        maxCharcter=q;
    }
}

cout<<max<<endl;
cout<<maxCharcter<<endl;

输出应该是 max=6 maxCharcter=a,但我得到了 max=11 maxCharcter=d。我做错了什么?

最佳答案

count 应该在你的第一个 for 循环中初始化

for(char q='a';q<='z';q++) {
   count = 0;
   //continue code here
}

关于c++ - 在 char 数组中查找出现次数最多的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11384881/

相关文章:

c++ - win32项目设计师

c# - 字符串输出 : format or concat in C#?

c - 在 C 中使用定界符拆分字符串 - 段错误

c++ - 为什么你必须定义一个空的构造函数c++

C++编译时函数执行

c++ - 文件IO从文件中读取多种类型

PHP 精确匹配一个字符串

C - 有没有办法用 'Enter' 以外的键终止字符串输入?

c++ - 将 int 数组更改为 char 数组

c - 如何连接两个字符数组以在 C 中从 fopen 打开文件?