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;
}

Also in this section

  1. How to print the elements of a C++ std::vector with GNU Debugger GDB ?
  2. How to convert string to lower case or UPPER case in C++ ?
  3. How to get command-line parameters in a C++ vector<string> ?
  4. How to split a string in C++ using STL ?
  5. How to sum elements of a C++ std::vector ?