convert string toupper and tolower in cpp

To convert a string to uppercase in C++, you can use the toupper() function from the <cctype> header. Here's how you can do it:

#include <iostream>
#include <cctype>
#include <string>

int main() {
    std::string str = "Hello, World!";

    for (char& c : str) {
        c = std::toupper(c);
    }

    std::cout << str << std::endl;

    return 0;
}

Explanation:

  1. Include the necessary headers:
#include <iostream>
#include <cctype>
#include <string>

The <iostream> header is needed for input and output operations. The <cctype> header provides the std::toupper() function. The <string> header is needed for the std::string class.

  1. Declare and initialize a string:
std::string str = "Hello, World!";

In this example, we initialize the str variable with the string "Hello, World!".

  1. Iterate over each character in the string:
for (char& c : str) {
    c = std::toupper(c);
}

We use a range-based for loop to iterate over each character in the str string. The char& c declaration creates a reference to each character in the string. We then call the std::toupper() function to convert each character to uppercase and assign it back to the original character.

  1. Output the modified string:
std::cout << str << std::endl;

Finally, we use std::cout to print the modified string to the console.

To convert a string to lowercase in C++, you can use the tolower() function from the <cctype> header. Here's how you can do it:

#include <iostream>
#include <cctype>
#include <string>

int main() {
    std::string str = "Hello, World!";

    for (char& c : str) {
        c = std::tolower(c);
    }

    std::cout << str << std::endl;

    return 0;
}

Explanation:

  1. Include the necessary headers:
#include <iostream>
#include <cctype>
#include <string>

The <iostream> header is needed for input and output operations. The <cctype> header provides the std::tolower() function. The <string> header is needed for the std::string class.

  1. Declare and initialize a string:
std::string str = "Hello, World!";

In this example, we initialize the str variable with the string "Hello, World!".

  1. Iterate over each character in the string:
for (char& c : str) {
    c = std::tolower(c);
}

We use a range-based for loop to iterate over each character in the str string. The char& c declaration creates a reference to each character in the string. We then call the std::tolower() function to convert each character to lowercase and assign it back to the original character.

  1. Output the modified string:
std::cout << str << std::endl;

Finally, we use std::cout to print the modified string to the console.