tags:

views:

156

answers:

5

hi,

Is there an inbuilt function to convert C++ string from upper case letters to lowercase letters ? If not converting it to cstring and using tolower on each char is the only option ?

Thank you very much in advance.

+1  A: 

There is no built-in function to do this, and doing it is surprisingly complicated, because of locales et al. If tolower does what you need, it may be your best bet.

anon
+8  A: 

If boost is an option:

#include <boost/algorithm/string.hpp>    

std::string str = "wHatEver";
boost::to_lower(str);

Otherwise, you may use std::transform:

std::string str = "wHatEver";
std::transform(str.begin(), str.end(), str.begin(), ::tolower);

You can also use another function if you have some custom locale-aware tolower.

ereOn
+5  A: 
std::transform(myString.begin(), myString.end(), myString.begin(), std::tolower);
TortoiseTNT
This and other transform + tolower answers should take into account that this won't necessarily compile, depending on what standard headers are included in this file. There is one `tolower` in `<cctype>` and an overload in `<locale>`. If both get included, you'll get a compiler error. See for example: http://stackoverflow.com/questions/1350380/problems-using-stl-stdtransform-from-cygwin-g
UncleBens
+1  A: 

Like ereOn says: std::transform(str.begin(), str.end(), str.begin(), std::tolower );

Or via for_each: std::for_each(str.begin(), str.end(), std::tolower );

Transform is probably better of the two.

graham.reeds
I bet so. for_each does not change str.
Luther Blissett
It was written off the cuff. You could use a lamda to call tolower for each character.
graham.reeds
A: 

For this problem you can use the STL's transform method to solve it:

std::string str = "simple";
std::transform(str.begin(), str.end(), str.begin(), std::tolower);
Nanne