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

1. Using std::transform

The standard algorithm std::transform is commonly used to apply a given function to all the elements of the specified range. This function can be a unary operation, a lambda, or an object implementing the () operator. It can be used as follows to capitalize a string, with the toupper function in the std namespace.

Download  Run Code

 
The above code can be further shortened with the tolower function in the global namespace which can be directly referenced with a name. It can be accessed with ::toupper, as shown below:

Download  Run Code

2. Using Boost

Alternatively, we can use the boost string algorithm to_lower to convert each character of the input sequence to lower case. It is available in the header <boost/algorithm/string.hpp>.

Download Code

 
The boost::algorithm::to_lower algorithm modifies the input sequence in-place. To avoid modifying the original string and return a copy instead, use boost::algorithm::to_lower_copy algorithm. It is available in the header <boost/algorithm/string.hpp>.

Download Code

3. Using std::for_each

Another option is to iterate the string using std::for_each and convert each character to uppercase. This would translate to the following code:

Download  Run Code

 
The std::for_each algorithm is available since C++11. The behavior of this function is equivalent to:

Download  Run Code

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