C++程序统计字符类型数量: 英文字母、空格、数字和其他
以下是一个 C++ 程序的示例,用于统计输入的一行字符中英文字母、空格、数字和其他字符的个数:
#include <iostream>
#include <cctype>
int main() {
std::string line;
std::cout << '请输入一行字符: '; // 使用单引号
std::getline(std::cin, line);
int letters = 0;
int spaces = 0;
int digits = 0;
int others = 0;
for (char ch : line) {
if (std::isalpha(ch)) {
letters++;
} else if (std::isspace(ch)) {
spaces++;
} else if (std::isdigit(ch)) {
digits++;
} else {
others++;
}
}
std::cout << '英文字母个数: ' << letters << std::endl; // 使用单引号
std::cout << '空格个数: ' << spaces << std::endl; // 使用单引号
std::cout << '数字个数: ' << digits << std::endl; // 使用单引号
std::cout << '其他字符个数: ' << others << std::endl; // 使用单引号
return 0;
}
这个程序首先提示用户输入一行字符,然后使用 getline 函数将输入存储在字符串变量 line 中。 然后,程序使用一个 for 循环遍历 line 中的每个字符。对于每个字符,它使用 isalpha、isspace 和 isdigit 函数来检查它是否是英文字母、空格或数字。如果不是这些字符之一,它将被视为其他字符。 最后,程序输出英文字母、空格、数字和其他字符的个数。
请注意,此程序假设输入的一行字符不包含中文字符。如果你想要处理中文字符,可以使用 Unicode 字符函数来进行相应的更改。
原文地址: https://www.cveoy.top/t/topic/cwAW 著作权归作者所有。请勿转载和采集!