What is the best way people have found to do String to Lower case / Upper case in C++?
The issue is complicated by the fact that C++ isn't an English only programming language. Is there a good multilingual method?
What is the best way people have found to do String to Lower case / Upper case in C++?
The issue is complicated by the fact that C++ isn't an English only programming language. Is there a good multilingual method?
std::string data = “Abc”;
std::transform(data.begin(), data.end(), data.begin(), ::toupper);
http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/
Also, CodeProject article for common string methods: http://www.codeproject.com/KB/stl/STL_string_util.aspx
You should also review this question. Basically the problem is that the standard C/C++ libraries weren't built to handle Unicode data, so you will have to look to other libraries.
This may change as the C++ standard is updated. I know the next compiler from Borland (CodeGear) will have Unicode support, and I would guess Microsoft's C++ compiler will have, or already has string libraries that support Unicode.
As Darren told you, the easiest method is to use std::transform.
But beware that in some language, like German for instance, there isn't always a one to one mapping between lower and uppercase. The "esset" lowercase character (look like the Greek character beta) is transformed to "SS" in uppercase.
> std::string data = “Abc”;
> std::transform(data.begin(), data.end(), data.begin(), ::toupper);
This will work, but this will use the standard "C" locale. You can use facets if you need to get a tolower for another locale. The above code using facets would be:
locale loc("");
const ctype<char>& ct = use_facet<ctype<char> >(loc);
transform(str.begin(), str.end(), std::bind1st(std::mem_fun(&ctype<char>::tolower), &ct));
What Steve says is right, but I guess that if your code had to support several languages, you could have a factory method that encapsulates a set of methods that do the relevant toUpper or toLower based on that language.
For copy-pasters hoping to use Nic Strong's answer, note the spelling error in "use_factet" and the missing third parameter to std::transform:
locale loc("");
const ctype<char>& ct = use_factet<ctype<char> >(loc);
transform(str.begin(), str.end(), std::bind1st(std::mem_fun(&ctype<char>::tolower), &ct));
should be
locale loc("");
const ctype<char>& ct = use_facet<ctype<char> >(loc);
transform(str.begin(), str.end(), str.begin(), std::bind1st(std::mem_fun(&ctype<char>::tolower), &ct));