题解 | #统计字符#
统计字符
https://www.nowcoder.com/practice/539054b4c33b4776bc350155f7abd8f5
#include <iostream> #include <string> using std::cin; using std::cout; using std::endl; using std::string; int char_num = 0; int space_num = 0; int digit_num = 0; int other_num = 0; bool isspace(char ch) { return ch == ' '; } void count_function(const string& str) { for (auto it = str.begin(); it != str.end(); it++) { if (isalpha(*it)) { // 判断是否为字母 char_num ++; } else if (isspace(*it)) { // 判断是否为空格 space_num++; } else if (isdigit(*it)) { // 判断是否为数字 digit_num ++; } else { //为其他字符 other_num++; } } cout << char_num << endl; cout << space_num << endl; cout << digit_num << endl; cout << other_num << endl; } int main(void) { string str; getline(cin, str); count_function(str); }