tr lowercase uppercase
To convert a string to lowercase or uppercase in C++, you can use the tolower()
and toupper()
functions respectively. Here are the steps to perform this conversion:
Include the necessary header file: Begin by including the
<cctype>
header file, which contains the functionstolower()
andtoupper()
. This header file provides functions for character handling and conversions.Declare the string: Declare a string variable and assign the desired string to it. For example,
std::string str = "Hello World";
.Convert to lowercase: To convert the string to lowercase, iterate through each character of the string using a loop. Inside the loop, call the
tolower()
function on each character and assign the result back to the corresponding position in the string.
cpp
for (int i = 0; i < str.length(); i++) {
str[i] = std::tolower(str[i]);
}
The tolower()
function takes a single character as input and returns the lowercase equivalent of that character. By iterating through each character of the string and applying the function, the entire string is converted to lowercase.
- Convert to uppercase: Similarly, to convert the string to uppercase, iterate through each character of the string using a loop. Inside the loop, call the
toupper()
function on each character and assign the result back to the corresponding position in the string.
cpp
for (int i = 0; i < str.length(); i++) {
str[i] = std::toupper(str[i]);
}
The toupper()
function takes a single character as input and returns the uppercase equivalent of that character. By iterating through each character of the string and applying the function, the entire string is converted to uppercase.
- Print the result: Finally, you can print the converted string using the
std::cout
statement.
cpp
std::cout << str;
This will display the converted string (lowercase or uppercase) on the console.
Here's a complete example that demonstrates the conversion of a string to lowercase and uppercase:
#include <iostream>
#include <cctype>
int main() {
std::string str = "Hello World";
// Convert to lowercase
for (int i = 0; i < str.length(); i++) {
str[i] = std::tolower(str[i]);
}
std::cout << "Lowercase: " << str << std::endl;
// Convert to uppercase
for (int i = 0; i < str.length(); i++) {
str[i] = std::toupper(str[i]);
}
std::cout << "Uppercase: " << str << std::endl;
return 0;
}
This program will output:
Lowercase: hello world
Uppercase: HELLO WORLD
Note that the tolower()
and toupper()
functions are part of the C standard library and can be used in C++ as well.