In this article, we are going to learn how to Convert String to LowerCase 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:
Ways to Convert String to LowerCase in C++
- Convert String to Lowercase using a for loop & ASCII.
- Convert String to Lowercase using Functions.
1. Convert String to Lowercase using for loop & ASCII
In this C++ code to Convert String to Lowercase, we used the if statement to check whether the character is
uppercase. If true, we are adding 32 to the ASCII Value to get the lowercase character.
#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 Lowercase = " << str1;
return 0;
}
Output
The String Converted to Lowercase = welcome to devenum tutorials
In the above example, instead of using the ‘A’ and ‘Z’ characters, You can specify the ASCII code numeric values of 65 and 90 also like if(str1[i] >= 65 && str1[i] <= 90)
2.Convert String to Lowercase using Functions
In this example, we have created two separate functions, where both of these are doing the upper to lower conversion of the string that we are passing as an argument.
#include<iostream>
#include<string>
using namespace std;
string UpperToLower(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 UpperToLower1(string str)
{
for (int i = 0; i < str.length(); i++)
{
if(str[i] >= 65 && str[i] <= 90)
{
str[i] = str[i] + 32;
}
}
return str;
}
int main()
{
string str1 = "WELCOME TO DEVENUM TUTORIALS";
string str2 = UpperToLower(str1);
cout<< "\nThe String Converted to Lowercase = " << str2;
string str3 = "PLEASE VISIT DEVENUM.COM TUTORIALS";
string str4 = UpperToLower1(str3);
cout<< "\nThe String Converted to Lowercase = " << str4;
return 0;
}
Output
The String Converted to Lowercase = welcome to devenum tutorials
The String Converted to Lowercase = please visit devenum.com tutorials