OneBite.Dev - Coding blog in a bite size

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:

  1. We first include the necessary libraries (<algorithm> and <string>) that give us access to the transform() method and string data type, respectively.

  2. We create a string s and initialize it to “hello world”.

  3. We use the transform() function, which applies a function to a range of elements in a container. In this case, we apply the toupper function to every character in string s.

  4. 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 where toupper 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.

  5. ::toupper is a standard library function that converts a character to uppercase if it is in lowercase; otherwise, the character itself is returned.

  6. Finally, we output the modified string s which is now turned into uppercase, and return 0 to end the main 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.

c-plus-plus