In this article, we are going to learn how to convert C++ string to lowercase string by using STL functions. We have traditional methods to convert strings to lowercase in C++, but here we are going to learn the advanced STL functions that can make the job easy and faster. We will learn to do this by using multiple techniques like:
- Convert String to Lowercase using STL tolower() function.
- Convert String to Lowercase using STL transform() function.
1. Convert String to Lowercase using STL tolower() function
In this example, we are going to use the tolower() function that is available in C++ STL Library. We are going to take a string and then use a simple for loop or while loop we are going to iterate on each character of this string to convert them to lowercase.
int tolower ( int c );
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str1 = "WELCOME TO DEVENUM TUTORIALS";
for (int i = 0; i < str1.length(); i++)
{
str1[i] = tolower(str1[i]);
}
cout<< "\nThe String Converted to Lowercase = " << str1;
return 0;
}
Output
The String Converted to Lowercase = welcome to devenum tutorials
2. Convert C++ String to LowerCase
In this example, we are making use of the while loop instead of the for loop.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str1 = "WELCOME TO DEVENUM TUTORIALS";
int index = 0;
while(index < str1.length())
{
if(isupper(str1[index]))
{
str1[index] = tolower(str1[index]);
}
index++;
}
cout<< "\nThe String Converted to Lowercase = " << str1;
return 0;
}
Output
The String Converted to Lowercase = welcome to devenum tutorials
3. Convert String to Lowercase using STL transform()
In this example, we are going to use the transform function which is available in STL. But if you want to use the transform() function then you must use C++ 20 Standard. This function will not work on older C++ standards.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str1 = "WELCOME TO DEVENUM TUTORIALS";
std:: transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
cout<< "\nThe String Converted to Lowercase = " << str1;
return 0;
}
Output
The String Converted to Lowercase = welcome to devenum tutorials
4.Using lambda with transform() function
In the below, the example we are going to use the lambda function in the transform() function to make use of the tolower() function.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str1 = "WELCOME TO DEVENUM TUTORIALS";
std::transform(str1.begin(), str1.end(), str1.begin(),
[](unsigned char c){ return std::tolower(c); }
);
cout<< "\nThe String Converted to Lowercase = " << str1;
return 0;
}
Output
The String Converted to Lowercase = welcome to devenum tutorials