views:

3637

answers:

6

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?

+19  A: 
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

Darren Kopp
You should say that one needs to #include <algorithm> to use transform
c0m4
I think it's better to use "dumb quotes" in such example of a string literal, rather than “smart quotes”. It makes it better in terms of copy-paste-compile.
Ron Klein
+2  A: 

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.

Rob Thomas
+1  A: 

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.

Steve Gury
+14  A: 
> 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));
Nic Strong
Good pointer thanks!
viksit
A: 

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.

axs6791
+3  A: 

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));
HeXetic
Thanks Hexetic, looks like GMan cleaned it up for us :)
Nic Strong