Convert String to UpperCase in C++

In this article, we are going to learn how to convert string to UpperCase in C++. In this tutorial, we are going to use the traditional C++ ways only, if you want to learn about advanced STL methods to do the string case conversion, please read here. We will learn to do this by using multiple techniques like:

  • Convert String to Uppercase using a for loop & ASCII.
  • Convert String to Uppercase using Functions.

1. Convert String to Uppercase using a for loop & ASCII


In this C++ code to Convert String to Uppercase, we used the if statement to check whether the character is
lowercase. If true, we are adding 32 to the ASCII Value to get the Uppercase character.

In below program instead of using the ‘a’ and ‘z’ characters, You can specify the ASCII code numeric values of 97 and 122 also like if(str1[i] >= 97 && str1[i] <= 122)

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string str1 = "Welcome To Devenum Tutorials";
	
	for (int i = 0; i < str1.length(); i++)
  	{
  		if(str1[i] >= 'a' && str1[i] <= 'z')
  		{
  			str1[i] = str1[i] - 32;
		}
  	}
  	
	cout<< "\nThe String Converted to Uppercase = " << str1;
		
 	return 0;
}

Output

The String Converted to Uppercase = WELCOME TO DEVENUM TUTORIALS

2. Convert String to Uppercase using Functions


In this example, we have created two separate functions, where both of these are doing the lower to the upper conversion of the string that we are passing as an argument.

#include<iostream>
#include<string>
using namespace std;

string LowerToUpper(string str)
{
	for (int i = 0; i < str.length(); i++)
  	{
  		if(str[i] >= 'a' && str[i] <= 'z')
  		{
  			str[i] = str[i] - 32;
		}
  	}
  	return str;
}
string LowerToUpper1(string str)
{
	for (int i = 0; i < str.length(); i++)
  	{
  		if(str[i] >= 97 && str[i] <= 122)
  		{
  			str[i] = str[i] - 32;
		}
  	}
  	return str;
}
int main()
{
	string str1 = "Welcome To Devenum Tutorials";
		
	string str2 = LowerToUpper(str1);
  	
	cout<< "\nThe String Converted to Uppercase = " << str2;
	
	string str3 = "Please Visit Devenum.Com Tutorials";
		
	string str4 = LowerToUpper1(str3);
  	
	cout<< "\nThe String Converted to Uppercase = " << str4;
		
 	return 0;
}

Output

The String Converted to Uppercase = WELCOME TO DEVENUM TUTORIALS
The String Converted to Uppercase = PLEASE VISIT DEVENUM.COM TUTORIALS