c++定义一个字符串,分别统计该字符串中大写字母小写字母和数字字符的个数,并利用函数输出统计结果
时间: 2023-11-16 11:13:27 浏览: 90
可以使用`string`类型来定义一个字符串,并利用`isupper()`、`islower()`和`isdigit()`函数来判断字符是否为大写字母、小写字母和数字字符。接下来,可以使用三个计数器分别统计这三类字符的个数,最后利用函数输出统计结果。以下是示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
void countCharacters(string str) {
int upperCount = 0, lowerCount = 0, digitCount = 0;
for (int i = 0; i < str.length(); i++) {
if (isupper(str[i])) {
upperCount++;
} else if (islower(str[i])) {
lowerCount++;
} else if (isdigit(str[i])) {
digitCount++;
}
}
cout << "Number of upper case characters: " << upperCount << endl;
cout << "Number of lower case characters: " << lowerCount << endl;
cout << "Number of digit characters: " << digitCount << endl;
}
int main() {
string str = "Hello World! 123";
countCharacters(str);
return 0;
}
```
输出结果为:
```
Number of upper case characters: 2
Number of lower case characters: 8
Number of digit characters: 3
```
阅读全文