C++练习25:计算输入字符串中每个字母出现的次数
题目
计算输入字符串中每个字母出现的次数,不区分大小写。
输入格式:输入长度不超过100的仅包含26个英文字母的字符串。
输出格式:输出每个字母出现的次数。
输出示例
Input:
Supercaliocious
Output:
the number of a : 1
the number of c : 2
the number of e : 1
the number of i : 2
the number of l : 1
the number of o : 2
the number of p : 1
the number of r : 1
the number of s : 2
the number of u : 2
代码
方法1:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string str;
cout << "Please input some text: ";
getline(cin,str);
transform(str.begin(), str.end(), str.begin(), ::tolower);
int cnt[256] = {};
for(int i = 0; i < str.size(); i++){
cnt[(int)str[i]]++;
}
for(int i = 0; i < 256; i++){
if(cnt[i] != 0){
cout << "the number of "<< (char)i << ": " << cnt[i] << endl;
}
}
}
方法2:
#include <iostream>
#include <string>
using namespace std;
int num[26];
int main() {
string data;
int index = -1;
char c;
cout<< "please input a string" << endl;
cin >> data;
for(int i = 0; i < data.size(); i++) {
if(data[i] >= 'a' && data[i] <= 'z')
index = data[i] - 'a';
else if(data[i] >= 'A' && data[i] <= 'Z')
index = data[i] - 'A';
if(index != -1)
num[index]++;
index = -1;
}
for(int j = 0; j < 26; j++) {
if(num[j] != 0) {
c= 'a' + j;
cout << "the number of " << c << " : " << num[j] << endl;
}
}
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)