Convert C++ String to Lower Case (or Upper Case)

I don’t usually need to convert string case in C++ so when the need comes up I’ve usually forgotten how to do it and have to Google.

While the Java String class has toLowerCase() and toUpperCase(), C++ std::string does not have such a utility method. Instead, you need to use the std::transform() function. Here’s some example code:

#include <iostream>
#include <string>
#include <utility>

int main(int argc, char* argv[])
{
        std::string s1 = "lowertoupper";
        std::string s2 = "UPPERTOLOWER";
        std::cout << s1 << " : ";
        std::transform(s1.begin(), s1.end(), s1.begin(), ::toupper);
        std::cout << s1 << std::endl;
        std::cout << s2 << " : ";
        std::transform(s2.begin(), s2.end(), s2.begin(), ::tolower);
        std::cout << s2 << std::endl;
        return 0;
}

Produces the following:

$ ./case.exe
lowertoupper : LOWERTOUPPER
UPPERTOLOWER : uppertolower

Note that while the Java toUpperCase() and toLowerCase() methods do not modify the original string, the std::transform function does.

Related Posts

Leave a Reply