string object to lowercase

Started by
1 comment, last by a light breeze 1 year, 2 months ago

Is this really the easiest way to take a C++ string object and make it lowercase:

#include <iostream>
#include <algorithm>
#include <cctype>
#include <string>

int main() {
   std::string str = "Hello, World!";
   
   // Convert the string to lowercase
   std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) {
       return std::tolower(c);
       });

   std::cout << str << std::endl; // Output: hello, world!

   return 0;
}

Thank you.

Advertisement

Sort of.

If you can guarantee that your input string is 7-bit ASCII, then you can get away with this:

std::transform(str.begin(), str.end(), str.begin(), std::tolower);

If you can't guarantee that your input string is 7-bit ASCII, then std::tolower is probably the wrong tool, because it uses the currently installed locale but only works for single-byte, one-character-in-one-character-out conversions. It doesn't work at all for utf-8 text, which is the 8-bit encoding you should always be using.

This topic is closed to new replies.

Advertisement