Convert a character to lowercase in C++

This article will discuss different ways to convert a character to lowercase in C++.

Convert a character to lowercase using tolower() function

C++ provides a function std::tolower(char c) to get a lowercase equivalent of a character. It accepts a character as an argument, and if this character is uppercase, it returns an lowercase equivalent of that character. We can use this function to convert a character to lowercase in C++. For example,

#include <iostream>

int main()
{
    char ch = 'B';

    // Convert a character to lowercase
    ch = std::tolower(ch);

    std::cout << ch <<std::endl;

    return 0;
}

Output:

b

It converted the uppercase character ‘B’ to an lowercase character ‘b’. If the provided character is not uppercase, then std::tolower() will return the same character. For example,

#include <iostream>

int main()
{
    char ch = '+';

    // Convert a character to lowercase
    ch = std::tolower(ch);

    std::cout << ch <<std::endl;

    return 0;
}

Output:

Advertisements
+

The provided character is not a uppercase character; therefore tolower() returned the same character.

Convert a character to lowercase by using the ASCII values

Every character in C++ has an ASCII value associated with it. In C++, the ASCII values of lowercase characters (i.e. ‘A’ to ‘Z’) in C++ are 65 to 90. The ASCII values of uppercase characters (i.e. ‘a’ to ‘z’) in C++ are 97 to 122. So, to convert a uppercase character to lowercase, we can add 32 to the character(its ASCII value). When we add anything to a character, the character gets automatically converted to an int (i.e. the ascii value), and the value is added. We can use this logic to convert a character to lowercase.

The steps are as follows,

  • Check if the provided character contains an alphabet and a uppercase character.
  • If yes, then add 32 to the character.

For example,

#include <iostream>

int main()
{
    char ch = 'B';

    if( isalpha(ch) && std::isupper(ch) )
    {
        ch += 32;
    }
    std::cout << ch <<std::endl;

    return 0;
}

Output:

b

It converted the uppercase character ‘B’ to an lowercase character ‘b’. Let’s check a negative example and convert the character ‘+’ to lowercase.

For example,

#include <iostream>

int main()
{
    char ch = '+';

    if( isalpha(ch) && std::isupper(ch) )
    {
        ch += 32;
    }
    std::cout << ch <<std::endl;

    return 0;
}

Output:

+

The provided character is not a uppercase character; therefore, our code didn’t change its value.

Summary:

We learned about two different ways to convert a character to lowercase in C++.

Advertisements

Thanks for reading.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top