用键盘输入任意一个字符串,分别统计出该字符串内英文大写字母、小写字母、数字、空格、及其它字符的个数。
时间: 2025-02-04 21:02:15 浏览: 50
为了统计字符串中英文大写字母、小写字母、数字、空格和其他字符的数量,你可以使用C++编写一个简单的程序。这个程序会遍历字符串中的每个字符,然后检查它的Unicode类别(category)来确定其类型。以下是代码实现:
```cpp
#include <iostream>
#include <string>
#include <cctype>
int countCharacters(const std::string& input) {
int upperCase = 0, lowerCase = 0, digits = 0, spaces = 0, others = 0;
for (char c : input) {
if (isupper(c)) // 英文大写字母
upperCase++;
else if (islower(c)) // 英文小写字母
lowerCase++;
else if (isdigit(c)) // 数字
digits++;
else if (isspace(c)) // 空格
spaces++;
else // 其他字符
others++; // 包括标点符号、特殊字符等
}
return {upperCase, lowerCase, digits, spaces, others};
}
int main() {
std::string input;
std::cout << "Enter a string: ";
getline(std::cin, input);
std::array<int, 5> result = countCharacters(input);
std::cout << "Uppercase letters: " << result[0] << "\n";
std::cout << "Lowercase letters: " << result[1] << "\n";
std::cout << "Digits: " << result[2] << "\n";
std::cout << "Spaces: " << result[3] << "\n";
std::cout << "Other characters: " << result[4] << "\n";
return 0;
}
```
当你运行此程序,并输入一个字符串后,它会显示出各个类别字符的数量。
阅读全文
相关推荐

















