Convert A String To Uppercase In C++
Code snippet for how to Convert A String To Uppercase In C++ with sample and detail explanation
In this article, we’ll discuss a few ways to convert a string into uppercase using C++. We’ll start with a simple method and then delve into an extended discussion of the internal mechanism involved in this operation.
Code snippet: String conversion using transform() method
Here is a simple code snippet:
#include <algorithm>
#include <string>
using namespace std;
int main() {
string s = "hello world";
transform(s.begin(), s.end(), s.begin(), ::toupper);
cout << s;
return 0;
}
Code Explanation for String conversion using transform() method
Let’s explain how this code works, step by step:
-
We first include the necessary libraries (
<algorithm>
and<string>
) that give us access to thetransform()
method and string data type, respectively. -
We create a string
s
and initialize it to “hello world”. -
We use the
transform()
function, which applies a function to a range of elements in a container. In this case, we apply thetoupper
function to every character in strings
. -
The
transform()
function has four parameters:s.begin()
,s.end()
,s.begin()
, and::toupper
. The first two parameters are iterators pointing to the beginning and end of the range wheretoupper
will be applied. The third parameter is where the transformed elements will be stored, and the fourth parameter is the function applied to each element in the range. -
::toupper
is a standard library function that converts a character to uppercase if it is in lowercase; otherwise, the character itself is returned. -
Finally, we output the modified string
s
which is now turned into uppercase, and return 0 to end themain
function.
Through this simple yet effective method, we’ve converted an entire string to uppercase in C++. You can apply this method whenever you need such string conversions, making it an essential tool in your C++ arsenal.