题目
统计元音
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 123364 Accepted Submission(s): 46618
Problem Description
统计每个元音字母在字符串中出现的次数。
Input
输入数据首先包括一个整数n,表示测试实例的个数,然后是n行长度不超过100的字符串。
Output
对于每个测试实例输出5行,格式如下:
a:num1
e:num2
i:num3
o:num4
u:num5
多个测试实例之间由一个空行隔开。
请特别注意:最后一块输出后面没有空行:)
Sample Input
2
aeiou
my name is ignatius
Sample Output
a:1
e:1
i:1
o:1
u:1
a:2
e:1
i:3
o:0
u:1
解题思路
因为输入的字符串中可能包含空格,所以我用string类的函数getline()从键盘输入字符串。要注意的地方就是输入n之后,缓冲区会留下一个‘\n’,即回车换行符,要对其进行处理。我的解决方案是定义一个字符c,用它来吃掉回车。
代码
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
char c;
scanf("%d%c", &n,&c); //C用来吃掉缓冲区的回车'\n',否则回车相当于输入一次字符串了
for (int num = 0; num < n; num++) {
string ss;
getline(cin, ss); //用getline函数从键盘输入字符串
int len = ss.length();
int count[5] = {0};
for (int i = 0; i < len; i++) {
if (ss[i] == 'a') count[0]++;
if (ss[i] == 'e') count[1]++;
if (ss[i] == 'i') count[2]++;
if (ss[i] == 'o') count[3]++;
if (ss[i] == 'u') count[4]++;
}
if (num > 0) cout << endl;
cout << "a:" << count[0] << endl;
cout << "e:" << count[1] << endl;
cout << "i:" << count[2] << endl;
cout << "o:" << count[3] << endl;
cout << "u:" << count[4] << endl;
}
return 0;
}