开发者社区> 问答> 正文

判断每个字母在string中出现的次数

写了一个c++程序判断每个字母在string中出现的次数 但为什么无论输入什么,全部字母都显示出现0次?

#include 
#include 
using namespace std;
int count(const char * const s)
{
int count = new int[26];
for (int i = 0; i < 26; i++)
count[i] = 0;
for (int j = 0; j < strlen(s); j++)
{
    count[s[j] - 'a']++;
}

return count;
}
int main()
{
char str[100]; //100 is big enough to contain the string
cin >> str[100];
int* p = count(str);
for (int a = 'a'; a <= 'z'; a++)
{
cout << (char)(a) << ": " << p[a - 'a'] << " times" << endl;
} 
return 0;
}

展开
收起
a123456678 2016-03-05 14:03:20 2221 0
1 条回答
写回答
取消 提交回答
  • cin >> str[100]

    1. 只是接受一个输入的字符,因为str[100]是char,而str才是指向char array的指针,cin对这两种类型处理是不一样的(即所谓重载);
    2. str[100]越界了,str[99]是最大的可访问区域;
    3. count是new出来的,返回后没有delete。
    2019-07-17 18:53:24
    赞同 展开评论 打赏
问答分类:
C++
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多