In this article we will discuss different ways to convert a string to upper case or lower case i.e.

  • STL
  • Boost String Algorithm Library

Convert a String to Upper Case using STL

C++ provides a function ::toupper() that converts a character to upper case character i.e.

To convert a complete string to upper case , just Iterate over all the characters in a string and call ::toupper() function each of them i.e.

Here we iterated over the string using std::for_each and while iterating we passed each character by reference to the passed callback i.e. a lambda function. This lambda function internally calls the ::toupper() to converts the case of each character.

Convert a String to Lower Case using STL

C++ provides a function ::tolower() that converts a character to lower case character i.e.

To convert a complete string to lower case , just Iterate over all the characters in a string and call ::tolower() function each of them i.e.

Complete Example is as follows,

Output:

::toupper() & ::tolower() only returns modified character if passed argument is actually an alphabet i.e. a-z or A-Z.

Issue with ::toupper() & ::tolower() is that they converts a single character at a time. To convert the case of a complete string we need to write extra code with these. Whereas, Boost String Algorithm Library provides a direct api that can be used to convert the case of a string i.e.

Convert a String to Upper Case using Boost Library

Boost String Algorithm Library provides a function Boost::to_upper() that can convert a complete string or a sequence to upper case i.e.

Convert a String to Lower Case using Boost Library

Boost String Algorithm Library provides a function Boost::to_lower() that can convert a complete string or a sequence to upper case i.e.

Complete example is as follows,

Output:

Creating a new string after case conversion

boost:to_upper() & boost::to_lower() converts the case of passed string. Whereas, many times we don’t want to modify the original string, we want to create a new string with converted case. For that boost provides to other function that creates a copy of passed string, then converts the case of new string and returns it. i.e.

Checkout complete example as follows,

Output:

 

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,