w3resource

C++ String Exercises: Change the case of each character of a given string

C++ String: Exercise-13 with Solution

Write a C++ program to change the case (lower to upper and upper to lower cases) of each character in a given string.

Visual Presentation:

C++ Exercises: Change the case of each character of a given string

Sample Solution:

C++ Code :

#include <iostream> // Include input/output stream library
#include <string> // Include string library for string operations
#include <cctype> // Include cctype library for character handling functions

using namespace std; // Using the standard namespace

// Function to change the case of characters in a string
string change_Case(string text) {

    // Loop through each character in the string
    for (int x = 0; x < text.length(); x++)
    {
        // Check if the character is uppercase
        if (isupper(text[x]))
        {
            text[x] = tolower(text[x]); // Convert uppercase to lowercase
        }
        else
        {
            text[x] = toupper(text[x]); // Convert lowercase to uppercase
        }
    }

    return text; // Return the modified string with changed cases
}

// Main function
int main() {

    // Output original strings and their modified versions after changing cases
    cout << "Original string: Python, After changing cases-> "<< change_Case("Python") << endl;
    cout << "Original string: w3resource,  After changing cases-> "<< change_Case("w3resource") << endl;
    cout << "Original string: AbcdEFH Bkiuer,  After changing cases-> "<< change_Case(" AbcdEFH Bkiuer") << endl;

    return 0; // Return 0 to indicate successful completion
}

Sample Output:

Original string: Python, After changing cases-> pYTHON
Original string: w3resource,  After changing cases-> W3RESOURCE
Original string: AbcdEFH Bkiuer,  After changing cases->  aBCDefh bKIUER

Flowchart:

Flowchart: Change the case of each character of a given string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: Insert a dash between two odd numbers in a string.
Next C++ Exercise: Find the numbers in a string and calculate the sum.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/cpp-exercises/string/cpp-string-exercise-13.php