c++判断字符串表达式s中小写字母个数
时间: 2024-02-06 15:10:11 浏览: 29
可以使用C++中的字符函数islower()来判断一个字符是否为小写字母,然后遍历字符串,统计其中小写字母的个数即可。
以下是示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello World";
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (islower(s[i])) {
count++;
}
}
cout << "The number of lowercase letters in the string is: " << count << endl;
return 0;
}
```
输出结果为:
```
The number of lowercase letters in the string is: 8
```
注意,需要包含头文件<ctype.h>或<cstring>来使用islower()函数。另外,也可以使用C++11中引入的range-based for循环简化代码,示例代码如下:
```c++
#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
int main() {
string s = "Hello World";
int count = 0;
for (char c : s) {
if (islower(c)) {
count++;
}
}
cout << "The number of lowercase letters in the string is: " << count << endl;
return 0;
}
```
输出结果与前面相同。