snippetcppCritical
How to convert an instance of std::string to lower case
Viewed 0 times
howinstancestdconvertstringcaselower
Problem
I want to convert a
Is there an alternative which works 100% of the time?
std::string to lowercase. I am aware of the function tolower(). However, in the past I have had issues with this function and it is hardly ideal anyway as using it with a std::string would require iterating over each character.Is there an alternative which works 100% of the time?
Solution
Adapted from Not So Frequently Asked Questions:
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
Be aware that
#include
#include
#include
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 = '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.Code Snippets
#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); });char asciitolower(char in) {
if (in <= 'Z' && in >= 'A')
return in - ('Z' - 'z');
return in;
}
std::transform(data.begin(), data.end(), data.begin(), asciitolower);Context
Stack Overflow Q#313970, score: 1165
Revisions (0)
No revisions yet.