如何在C++中将std::string字符串转换为小写?
各位同行,大家好!
我是C++新手(之前用Python写代码),遇到了一个看似简单的任务:需要将std::string对象中的所有字符转换为小写。在Python中,我只需写"HELLO".lower()就搞定了。但在C++中,我陷入了困境。
以下是我的代码,它无法正常工作:
```cpp
#include
#include
int main() {
std::string text = "HELLO WORLD!";
std::string lower_text = std::tolower(text); // 错误!
std::cout << lower_text << std::endl;
return 0;
}
```
编译器报错:`cannot convert 'std::string' to 'int' for argument '1' to 'int tolower(int)'`。我明白了,`std::tolower`只适用于单个字符(类型为`int`),而不能直接处理整个字符串。
我尝试手动编写循环:
```cpp
for (size_t i = 0; i < text.length(); ++i) {
text[i] = std::tolower(text[i]);
}
```
这样确实有效,但我觉得这太繁琐且不优雅。C++中是否有标准方法可以一行代码完成这个操作?