Math-Linux.com

Knowledge base dedicated to Linux and applied mathematics.

Home > C++ > FAQ C++ > FAQ C++ - STL > How to convert string to lower case or UPPER case in C++ ?

How to convert string to lower case or UPPER case in C++ ?

How to convert string to lower case or UPPER case in C++ ?

The fast way to convert is to use transform algorithm associated to lower and upper function.

#include <algorithm>
#include <string>
#include <iostream>
using namespace std;

int main(){
string data = "ABc1#@23yMz";
transform(data.begin(), data.end(), data.begin(),(int (*)(int))toupper);
cout << data << endl;
transform(data.begin(), data.end(), data.begin(),(int (*)(int))tolower);
cout << data << endl;
}

Result:

ABC1#@23YMZ
abc1#@23ymz

To avoid pointers to function, use operator ::

#include <algorithm>
#include <string>
#include <iostream>
using namespace std;

int main(){
string data = "ABc1#@23yMz";
transform(data.begin(), data.end(), data.begin(),::toupper);
cout << data << endl;
transform(data.begin(), data.end(), data.begin(),::tolower);
cout << data << endl;
}

Any message or comments?

comments powered by Disqus