c++怎么把一串字符串里面的大写字母转为小写字母,其他数字部分不改变
时间: 2024-03-29 16:40:06 浏览: 21
可以使用标准库中的 `std::transform` 算法和 `std::tolower` 函数来实现将字符串中的大写字母转换为小写字母,其他数字部分不变。以下是一个示例代码:
```c++
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World! 123";
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) { return std::tolower(c); });
std::cout << str << '\n'; // 输出 "hello, world! 123"
return 0;
}
```
在上面的代码中,我们定义了一个 lambda 函数作为 `std::transform` 的第四个参数,该函数将每个字符转换为小写字母并返回。此外,我们使用了 `std::tolower` 函数来实现字符的转换。
相关问题
给我C++输入一个带空格的字符串,并把所有大写字母转为小写字母的代码
以下是C++输入一个带空格的字符串,并把所有大写字母转为小写字母的示例代码:
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cout << "请输入一个带空格的字符串:";
getline(cin, str); // 输入带空格的字符串,使用getline()函数读取整行字符串
for (int i = 0; i < str.length(); i++) {
if (str[i] >= 'A' && str[i] <= 'Z') { // 判断是否为大写字母
str[i] = str[i] + 32; // 将大写字母转为小写字母
}
}
cout << "转换后的字符串为:" << str << endl;
return 0;
}
```
以上代码使用了string类型的变量存储输入的带空格字符串,并使用getline()函数读取整行字符串。然后,使用for循环遍历字符串中的每个字符,判断是否为大写字母,如果是,则将其转为小写字母。最后,使用cout输出转换后的字符串。
统一字符串中的大写字母,小写字母和数字的个数的c++代码
以下是统计字符串中大写字母、小写字母和数字的个数的C++代码:
```c++
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
int upper = 0, lower = 0, digit = 0;
cout << "请输入一个字符串:";
getline(cin, str);
for(int i = 0; i < str.length(); i++)
{
if(isupper(str[i])) // 判断是否为大写字母
upper++;
else if(islower(str[i])) // 判断是否为小写字母
lower++;
else if(isdigit(str[i])) // 判断是否为数字
digit++;
}
cout << "大写字母个数:" << upper << endl;
cout << "小写字母个数:" << lower << endl;
cout << "数字个数:" << digit << endl;
return 0;
}
```
这段代码通过循环遍历字符串中的每个字符,并使用`isupper()`、`islower()`和`isdigit()`等函数判断每个字符是否为大写字母、小写字母或数字,从而统计它们的个数。