In this article, we are going to learn how to convert String to UpperCase using STL in C++. We have traditional methods to convert strings to Upper 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 Uppercase using STL toupper() function.
- Convert String to Uppercase using STL transform() function.
1. Convert String to Uppercase 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 Uppercase.
int toupper ( 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] = toupper(str1[i]);
}
cout<< "\nThe String Converted to Uppercase = " << str1;
return 0;
}
Output
The String Converted to Uppercase = WELCOME TO DEVENUM TUTORIALS
2. for loop to Convert String to UpperCase
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(islower(str1[index]))
{
str1[index] = toupper(str1[index]);
}
index++;
}
cout<< "\nThe String Converted to Uppercase = " << str1;
return 0;
}
Output
The String Converted to Uppercase = WELCOME TO DEVENUM TUTORIALS
3. Convert String to Uppercase using STL transform() function
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(), ::toupper);
cout<< "\nThe String Converted to Uppercase = " << str1;
return 0;
}
Output
The String Converted to Uppercase = WELCOME TO DEVENUM TUTORIALS
4. Using lambda function in transform()
In the below, example we are going to use the lambda function in the transform() function to make use of the toupper() 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::toupper(c); }
);
cout<< "\nThe String Converted to Uppercase = " << str1;
return 0;
}
Output
The String Converted to Uppercase = WELCOME TO DEVENUM TUTORIALS