句子成分分析(C++)
生活随笔
收集整理的這篇文章主要介紹了
句子成分分析(C++)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
從鍵盤輸入n個英文句子(“.”、“?”和“!”表示結束),每次輸入一句,分別統計輸出每個句子的大寫字母個數、小寫字母個數、數字個數、空格個數和其他字符個數,最后輸出全部句子的統計結果。
題目:
從鍵盤輸入n個英文句子(“.”、“?”和“!”表示結束),每次輸入一句,分別統計輸出每個句子的大寫字母個數、小寫字母個數、數字個數、空格個數和其他字符個數,最后輸出全部句子的統計結果。
- 每個句子不知道有多長,所以不適合用char []型存儲,所以可以選擇用string;
- 由于不知道會輸入多少個句子,所以可以選擇動態數組vector來存儲每個string;
- 判斷字符類型可以用庫函數:<cctype>
- 各種句子成分類型可以寫在一個結構體內;
具體代碼如下:
#include <iostream> #include <vector> #include <cctype> #include <string> using std::cin; using std::cout; using std::endl; using std::string; void analyse(string & ); struct component {int uppercase;int lowercase;int digit;int space; int other; }cp; int main() {cout << "請輸入幾個句子,每個句子以“.”,“?”或“!”結尾,以一個'.'作為最后一個句子。" << endl;std::vector<string> sentences;char ch=' ';string str("");while(str != "."){str.erase(str.begin(),str.end());ch = ' ';while(ch!='.' && ch!='?' && ch!='!'){cin.get(ch);if (ch == '.' || ch == '?' || ch == '!')cin.get();str += ch;}sentences.push_back(str);}for (decltype(sentences.size()) i = 0; i < sentences.size(); i++){if (i == sentences.size()-1)cout << endl << "總句子分析:" << endl;elsecout << endl << "第" << i + 1 << "個句子分析:" << endl;analyse(sentences[i]);}cout << "bye!";system("pause");return 0; } void analyse(string & str) { static component sum_cpn={0};if (str=="."){cout << "總小寫字母數:" << sum_cpn.lowercase << endl<< "總大寫字母數:" << sum_cpn.uppercase << endl<< "總數字數:" << sum_cpn.digit << endl<< "總空格數:" << sum_cpn.space << endl<< "總其他字符數:" << sum_cpn.other << endl;return;}component cpn={0,0,0,0,0};for (decltype(str.size()) i = 0; i < str.size(); i++){if (isupper(str[i])){cpn.uppercase++;sum_cpn.uppercase++;} else if (islower(str[i])){cpn.lowercase++;sum_cpn.lowercase++;}else if (isdigit(str[i])){cpn.digit++;sum_cpn.digit++;}else if (isspace(str[i])){cpn.space++;sum_cpn.space++;}else{cpn.other++;sum_cpn.other++;}}cout << "小寫字母數:" << cpn.lowercase << endl<< "大寫字母數:" << cpn.uppercase << endl<< "數字數:" << cpn.digit << endl<< "空格數:" << cpn.space << endl<< "其他字符數:" << cpn.other << endl; }總結
以上是生活随笔為你收集整理的句子成分分析(C++)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Restful API设计规范及实战
- 下一篇: 【通讯录自动导入】txt格式转vcf格式