I want to convert a std::string to lowercase. I am aware of the function tolower(), however in the past I have had issues with this function and it
Since none of the answers mentioned the upcoming Ranges library, which is available in the standard library since C++20, and currently separately available on GitHub as range-v3, I would like to add a way to perform this conversion using it.
To modify the string in-place:
str |= action::transform([](unsigned char c){ return std::tolower(c); });
To generate a new string:
auto new_string = original_string
| view::transform([](unsigned char c){ return std::tolower(c); });
(Don't forget to #include and the required Ranges headers.)
Note: the use of unsigned char as the argument to the lambda is inspired by cppreference, which states:
Like all other functions from
, the behavior ofstd::toloweris undefined if the argument's value is neither representable asunsigned charnor equal toEOF. To use these functions safely with plainchars (orsigned chars), the argument should first be converted tounsigned char:char my_tolower(char ch) { return static_cast(std::tolower(static_cast (ch))); } Similarly, they should not be directly used with standard algorithms when the iterator's value type is
charorsigned char. Instead, convert the value tounsigned charfirst:std::string str_tolower(std::string s) { std::transform(s.begin(), s.end(), s.begin(), // static_cast(std::tolower) // wrong // [](int c){ return std::tolower(c); } // wrong // [](char c){ return std::tolower(c); } // wrong [](unsigned char c){ return std::tolower(c); } // correct ); return s; }