This article will discuss different ways to convert a character to uppercase in C++.
Table of Contents
- Convert a character to uppercase using toupper() function
- Convert a character to uppercase using the ASCII values
Convert a character to uppercase using toupper() function
C++ provides a function std::toupper(char c) to get a uppercase equivalent of a character. It accepts a character as an argument, and if this character is lowercase, it returns an uppercase equivalent of that character. We can use this function to convert a character to uppercase in C++. For example,
#include <iostream> int main() { char ch = 'i'; // Convert a character to uppercase ch = std::toupper(ch); std::cout << ch <<std::endl; return 0; }
Output:
I
It converted the lowercase character ‘i’ to an uppercase character ‘I’. If the provided character is not lowercase, then std::toupper() will return the same character. For example,
#include <iostream> int main() { char ch = '+'; // Convert a character to uppercase ch = std::toupper(ch); std::cout << ch <<std::endl; return 0; }
Output:
+
The provided character is not a lowercase character; therefore toupper() returned the same character.
Frequently Asked:
- How to remove Substrings from a String in C++
- Replace First Character in a string in C++
- Convert Char Array to an integer in C++
- Split a String using Delimiter in C++
Convert a character to uppercase by using the ASCII values
Every character in C++ has an ASCII value associated with it. In C++, the ASCII values of uppercase characters (i.e. ‘A’ to ‘Z’) in C++ are 65 to 90. The ASCII values of lowercase characters (i.e. ‘a’ to ‘z’) in C++ are 97 to 122. So, to convert a lowercase character to uppercase, we can subtract 32 from the character(its ASCII value). When we subtract anything from a character, the character gets automatically converted to an int (i.e. the ascii value), and the value is subtracted. We can use this logic to convert a character to uppercase.
The steps are as follows,
- Check if the provided character contains an alphabet and a lowercase character.
- If yes, then subtract 32 from the character.
For example,
#include <iostream> int main() { char ch = 'i'; // Check if char is a lowercase alphabet if( isalpha(ch) && islower(ch) ) { // Convert a character to uppercase ch = ch - 32; } std::cout << ch <<std::endl; return 0; }
Output:
I
It converted the lowercase character ‘i’ to an uppercase character ‘I’. Let’s check a negative example and convert the character ‘+’ to uppercase.
For example,
#include <iostream> int main() { char ch = '+'; // Check if char is a lowercase alphabet if( isalpha(ch) && islower(ch) ) { // Convert a character to uppercase ch = ch - 32; } std::cout << ch <<std::endl; return 0; }
Output:
+
The provided character is not a lowercase character; therefore, our code didn’t change its value.
Summary:
We learned about two different ways to convert a character to uppercase in C++.