How to convert an instance of std string to lower case

0 votes
I'd want to change a std::string to lowercase.

I am aware of the lower function ().

However, I've had problems with this method in the past, and using it with a std::string would require iterating over each character.

Is there an option that works 100% of the time?
Aug 2, 2022 in C++ by Nicholas
• 7,760 points
3,034 views

1 answer to this question.

0 votes
#include <algorithm>
#include <cctype>
#include <string>

std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(),
    [](unsigned char c){ return std::tolower(c); });

You're not going to get away with not going over each character. 

Otherwise, there is no way to tell whether the character is lowercase or uppercase.

If you despise tolower(), here's a customised ASCII-only solution I don't recommend:

char asciitolower(char in) {
    if (in <= 'Z' && in >= 'A')
        return in - ('Z' - 'z');
    return in;
}

std::transform(data.begin(), data.end(), data.begin(), asciitolower);

Tolower() can only do single-byte character substitutions, which is inconvenient for many scripts, notably those that use a multi-byte encoding like UTF-8.

answered Aug 2, 2022 by Damon
• 4,960 points

Related Questions In C++

0 votes
0 answers

How to initialize an std::string with a length?

How can I correctly initialise a string if its length is specified at build time? #include <string> int length = 3; string word[length]; //invalid ...READ MORE

Jul 27, 2022 in C++ by Nicholas