C++,大神帮忙!一函数统计字符串中各个字母(不区分大小写)出现的频!

同时找出频率出现最高的字母及次数。我编了一下,求大神指点!
#include"iostream.h"
#include"string.h"
#include"stdio.h"
void freq(char s[],int p[],char &chmax,int &max);
{
int x;
for(int i=0;s[i]!='\0';i++)
for(int j=0;p[j]!='\0';j++)
if(s[i]==p[j])
x++;
cout<<p[j]<<"----"<<x<<endl;
}
void main()
{
char s1[80],chmax1;
int s2[80],max1;
gets(s1);
freq(s1,s2,chmax1,max1);
cout<<"频率出现最高的字母:"<<max1<<"----"<<chmax1;
}

你的s2没赋值而且你把int和char进行比较是什么意思。。

给你写了一个

#include<iostream>
using namespace std;

int main()
{
int cnt[26]; //用于计数,cnt[0]记录a出现的次数
memset(cnt, 0, sizeof(cnt)); //清空该数组
    char s[80];
gets(s);
for(int i = 0; i < strlen(s); i++)
{
if(s[i] >= 'a' && s[i] <= 'z')
{
cnt[s[i] - 'a'] ++;
}
else if(s[i] >= 'A' && s[i] <= 'Z')
{
cnt[s[i] +32 - 'a'] ++;
}
else;
}
int max = -1, pos = -1;
for(int i = 0; i < 26; i++)
{
if(cnt[i] > max)
{
max = cnt[i];
pos = i;
}
}
cout << (char)(pos + 'a') << " " << cnt[pos] << endl;
return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-04-13
建议你使用 std::map<char,int> 这东西,非常方便
#include<map>
#include<ctype>

std::map<char,int> alphaMap;
alphaMap.clear();

char ch;
读取一个字母到 ch 后
ch = tolower(ch) //转小写
alphaMap[ch] +=1;//std::map 对与没有存储的数据来会自动初始化一个并根据数据类型复制,例如 int 自动 初始化为0
最后只需要遍历这个alphaMap 就可以了其中 key就是出现屏幕最高的字母 value 就是出现的次数
std::map<char,int>::iterator maxIt = alphaMap.begin()
for(std::map<char,int>::iterator it = alphaMap.begin(), it!= alphaMap.end(), ++it)
{
if (it->second > maxIt->second)
maxIt = it;
}
std::cout<<"频率出现最高的字母:"<<it->first <<"----"<< it->second;
相似回答