c++的string转大写
时间: 2023-07-14 11:07:23 浏览: 146
在 C++ 中,要将字符串转换为大写,您可以使用 `<cctype>` 头文件中的 `toupper()` 函数。以下是一个示例:
```cpp
#include <iostream>
#include <string>
#include <cctype>
int main() {
std::string myString = "hello world";
for (char& c : myString) {
c = std::toupper(c);
}
std::cout << myString << std::endl;
return 0;
}
```
这段代码将迭代字符串中的每个字符,并使用 `std::toupper()` 函数将其转换为大写。最后,通过 `std::cout` 打印出结果。
输出将是:
```
HELLO WORLD
```
这样,您就可以将 C++ 的 `std::string` 转换为大写字母。
相关问题
c++string字符串大写转小写
可以通过循环遍历字符串并调用 `tolower()` 函数来实现将大写字母转换为小写字母,例如:
```c++
#include <iostream>
#include <string>
int main() {
std::string s = "HELLO WORLD!";
for (char& c : s) {
c = tolower(c);
}
std::cout << s << std::endl; // 输出 "hello world!"
return 0;
}
```
在循环中,将字符串中的每个字符都转换为小写字母,并将其重新赋值给原来的位置。最后输出转换后的字符串即可。
c++ stringstream 大写
要将 C++ stringstream 中的字符串转换为大写,您可以使用 std::toupper 函数。首先,将 stringstream 中的字符串提取出来,然后使用 std::transform 函数将每个字符转换为大写,并将结果存储回 stringstream。以下是一个示例代码:
```cpp
#include <iostream>
#include <sstream>
#include <algorithm> // for std::transform
#include <cctype> // for std::toupper
int main() {
std::stringstream ss("Hello, World!");
std::string str = ss.str(); // 提取字符串
// 将字符串转换为大写
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c){ return std::toupper(c); });
ss.str(str); // 将结果存回 stringstream
std::cout << ss.str() << std::endl; // 输出大写字符串
return 0;
}
```
运行以上代码,输出将会是 "HELLO, WORLD!"。