Mark As Completed Discussion

String Case Conversion

In C++, you can change the case of a string by converting all its characters to uppercase or lowercase.

To convert a string to uppercase, you can use the std::transform function from the <algorithm> header along with the ::toupper function from the <cctype> header. This function will convert each character in the string to its uppercase form.

To convert a string to lowercase, you can use the same std::transform function with the ::tolower function, which will convert each character to its lowercase form.

Here's an example:

TEXT/X-C++SRC
1#include <iostream>
2#include <algorithm>
3#include <cctype>
4
5int main() {
6  std::string str = "Hello World";
7
8  // Convert to uppercase
9  std::transform(str.begin(), str.end(), str.begin(), ::toupper);
10  std::cout << "Uppercase: " << str << std::endl;
11
12  // Convert to lowercase
13  std::transform(str.begin(), str.end(), str.begin(), ::tolower);
14  std::cout << "Lowercase: " << str << std::endl;
15
16  return 0;
17}

In this example, we start with the string "Hello World". We use std::transform function along with ::toupper to convert the characters to uppercase, and then std::transform with ::tolower to convert the characters back to lowercase.

The output of the code snippet will be:

SNIPPET
1Uppercase: HELLO WORLD
2Lowercase: hello world
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment