Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to convert an instance of std::string to lower case

I need to change a std::string over to lowercase. I'm mindful of the capacity tolower(). However, previously, I have had issues with this capacity and it is not really ideal at any rate as utilizing it with a std::string would require repeating over each character.

Is there an elective that works 100% of the time?
by

2 Answers

espadacoder11

#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 really not going to get away without iterating through each character. There's no way to know whether the character is lowercase or uppercase otherwise.

If you really hate tolower(), here's a specialized ASCII-only alternative that I don't recommend you use:

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

std::transform(data.begin(), data.end(), data.begin(), asciitolower);
Be aware that tolower() can only do a per-single-byte-character substitution, which is ill-fitting for many scripts, especially if using a multi-byte-encoding like UTF-8.
sandhya6gczb
Boost provides an algorithm of this

#include <boost/algorithm/string.hpp>

std::string str = "HELLO, WORLD!";
boost::algorithm::to_lower(str); // modifies str

And for non-in-place

#include <boost/algorithm/string.hpp>

const std::string str = "HELLO, WORLD!";
const std::string lower_str = boost::algorithm::to_lower_copy(str);

Login / Signup to Answer the Question.