题解 | #统计字符串中各类型字符的个数#
统计字符串中各类型字符的个数
https://www.nowcoder.com/practice/d5b44c494ed24d8ebb10607c469280e3
#include <cctype> #include <iostream> #include <string> #include <vector> using namespace std; int main() { vector<char> str; char input; while (cin.get(input) && input != '\n') { str.push_back(input); } int numAlpha = 0; int numDigit = 0; int numSpace = 0; int numOther = 0; for(char g : str){ if(isalpha(g)){ numAlpha += 1; } else if(isdigit(g)){ numDigit += 1; } else if(isspace(g)){ numSpace += 1; } else{ numOther += 1; } } cout<<"letter:"<<numAlpha<<' '; cout<<"digit:"<<numDigit<<' '; cout<<"space:"<<numSpace<<' '; cout<<"other:"<<numOther<<' '; }
使用vector容器存储输入字符,直到遇到回车键,然后遍历vector容器,通过isalpha()等函数判断字符类型从而统计个数,最后输出结果。