Convert String to lowercase in C++

Convert String to lowercase in C++

In this post, we will see how to convert String to lowercase in C++.

We can assume strings to be an array of characters. Each character has a specific ASCII value, and characters with different cases, for example, a and A have different ASCII values.

Ways to Convert a String to Lowercase in C++

We will discuss different methods on how to convert a string to all lowercase characters in C++.

Using the tolower() and transform() function

The tolower() function in C++ returns a given character in lowercase. This function is defined in the cctype header file. We can apply a given function to all elements of an array using the std::transform() function. The transform() is defined in the algorithm header file.

Using this method, we will apply the tolower() function to every character of a string.

See the following example.

Output:

blog

In the above example, we apply the tolower() function to every character of the string s using the std::transform() function and display it.

We can also eliminate the use of the tolower() function by creating our own function that converts a character to lowercase. This function will use the ASCII value to return the corresponding lowercase of a character.

For example,

Output:

blog

In the above example,

  • The fun() function converts a given character to lowercase.
  • We apply the fun() function to every character using the transform() function.

Using the for loop

We can use the for loop to iterate over the string and convert each character to lowercase. To carry out the conversion, we can either use the tolower() function or the user-defined method used in the previous example.

Both are demonstrated below.

Output:

blog
blog

In the above example,

  • We used the for loop to traverse through the string.
  • Every character was converted to lowercase and displayed.
  • In the first loop, we used the tolower() function. In this case, it will return the ASCII value, so we convert it to a character using the char() function.
  • In the second loop, we used the fun() function used in the earlier example.

Using the boost library

The boost library in C++ provides two methods to convert a given string to lowercase. The to_lower() function from this library modifies the original string and converts it into lowercase. The to_lower_copy() function creates a copy of the string and converts it to lowercase.

We will use both these functions below.

Output:

blog
blog

In the above example,

  • We use the to_lower_copy() function to convert the string to lowercase and store it in a new string.
  • The to_lower() function modifies the original string.

That’s all about how to covnert String to lowercase in C++.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *