Count words and letters-计算用户输入一行文本中的单词数和每个字母出现次数
//Count words and letters
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cctype>
using namespace std;
int main()
{
int words_count = 1;
int char_count[26] = {0};
char ch;
cout<<"Input a line \n";
while((ch = cin.get()) != ‘\n‘)
{
if(ch == ‘ ‘)
words_count++;
if(isalpha(ch))
{
ch = tolower(ch);
char_count[static_cast<int>(ch) - 97]++;
}
}
//for(int i = 0;i<26;i++)
//cout<<char_count[i]<<" ";
cout<<words_count<<" words\n";
for(int i = 0;i < 26;i++)
if(char_count[i] != 0)
{
cout<<char_count[i]<<"\t"<<static_cast<char>(97 + i)<<endl;
}
return 0;
}结果:
Input a line I say Hi. 3 words 1 a 1 h 2 i 1 s 1 y
Input a line aaa bb cccc dddd. 4 words 3 a 2 b 4 c 4 d
Count words and letters-计算用户输入一行文本中的单词数和每个字母出现次数
原文:http://9320314.blog.51cto.com/9310314/1550652