This post will discuss how to convert a string to lowercase in C++.

1. Using range-based for-loop

A simple approach is to create our own routine for converting a character to its lowercase version. The idea is to iterate the string using a range-based for-loop with a reference variable and call our conversion routine for each character.

Download  Run Code

Output:

abc

2. Using std::for_each function

A less verbose solution is to use the standard algorithm std::for_each, which uses a loop under the hood and applies a specified function to every string element. The specified function may be a unary function, a lambda expression, or an object of a class overloading the () operator.

We have used the std::tolower function in the following example, which converts the given character to lowercase. The argument should be converted to unsigned char; otherwise, the behavior is undefined to use it safely with signed chars.

Download  Run Code

Output:

convert
string
lowercase

3. Using std::transform function

Another good alternative is to use the STL algorithm std::transform, which applies an operation to elements of the specified range and stores the result in another range, which begins at the specified output iterator. The operation may be a unary operation function, a lambda expression, or an object of a class implementing the () operator.

Download  Run Code

Output:

convert
string
lowercase

4. Using Boost Library

Finally, we can use boost::algorithm::to_lower to convert each element of std::string to lower case. We can also use boost::algorithm::to_lower_copy, but it returns a copy of the string object and doesn’t modify the given string.

Download Code

Output:

abcd

That’s all about converting a string to lowercase in C++.