Count words and letters-計算用戶輸入一行文本中的單詞數和每個字母出現次數

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章