如何纪录字符串中字母出现的字数

比如 aabxdfdddd

a: 2  

b:1

d:5

f :1

你好多少钱
浏览 1310回答 3
3回答

请输入你的用户名

#include<iostream> using namespace std; void main() { char s[100], Letter; cout << "输入字符串:"; cin >> s; int count[26] = { 0 }, i, s_i; // 统计26个字母出现的次数 int n = strlen(s);   //计数器 for (i = 0; i<n; i++) { s_i = s[i] - 'a'; count[s_i]++; // 字符 } for (i = 0; i<26; i++) { if (count[i] != 0) // 若该字母出现 { Letter = 'a' + i; cout << Letter << " : " << count[i] << endl; // 输出 } } }

慕容5123895

#include<iostream>#include<string>using namespace std;int main(){     cout << "请输入字符串:" << endl;     string s;     getline(cin, s);     int count = s.size();     char letter[26] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };     for (int i = 0; i < 26; i++)     {             int num = 0;             for (int j = 0; j < count; j++)             {                     if (s[j] == letter[i])                     {                                 num++;                     }             }             if (num > 0)             {                     cout << letter[i] << ":" << num << endl;             }             num = 0;         }         system("pause");         return 0;}
打开App,查看更多内容
随时随地看视频慕课网APP