对于string类型字符串实现大小写互转
时间: 2023-08-05 19:41:06 浏览: 55
可以使用C++中的标准库函数`toupper()`和`tolower()`来实现字符串的大小写互转。
将字符串中的所有小写字母转换成大写字母,可以使用如下代码:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = "Hello World!";
transform(str.begin(), str.end(), str.begin(), ::toupper);
cout << str << endl; // 输出:HELLO WORLD!
return 0;
}
```
将字符串中的所有大写字母转换成小写字母,可以使用如下代码:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = "Hello World!";
transform(str.begin(), str.end(), str.begin(), ::tolower);
cout << str << endl; // 输出:hello world!
return 0;
}
```
需要注意的是,`transform()`函数需要在头文件`<algorithm>`中引用,并且第四个参数需要使用`::toupper`或`::tolower`来指定转换的类型。