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:
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:
1Uppercase: HELLO WORLD
2Lowercase: hello world
xxxxxxxxxx
int main() {
std::string str = "Hello World";
// Convert to uppercase
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
std::cout << "Uppercase: " << str << std::endl;
// Convert to lowercase
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
std::cout << "Lowercase: " << str << std::endl;
return 0;
}