How to convert std::string to lowercase in C++?
Hi everyone! I'm new to C++ and writing a small text processing program. I need to convert all characters in a string to lowercase. I know that in C there is the tolower() function from , but it only works with individual characters (int). How can I apply it to the entire std::string?
I tried writing a loop like this:
```cpp
#include
#include
#include
int main() {
std::string str = "Hello World!";
for (int i = 0; i < str.size(); ++i) {
str[i] = tolower(str[i]);
}
std::cout << str << std::endl;
return 0;
}
```
The code compiles, but I'm not sure if it's correct and safe. Is there a more idiomatic way using STL? I've heard about std::transform, but I don't understand how to apply it together.
No answers yet.
Log in to leave an answer