Changing Case of a String

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 129:- Changing Case of a String

In C and C++, you can change the case of a string by converting the characters to uppercase or lowercase. The standard library provides functions for this purpose. Here are examples of how to change the case of a string in both C and C++:

Changing Case of a String (C++):

cppCopy code

#include <iostream> #include <string> #include <algorithm> int main() {    std::string str = "Hello, World!";        // Convert to uppercase    std::transform(str.begin(), str.end(), str.begin(), ::toupper);    std::cout << "Uppercase string: " << str << std::endl;    // Convert to lowercase    std::transform(str.begin(), str.end(), str.begin(), ::tolower);    std::cout << "Lowercase string: " << str << std::endl;    return 0; }

Changing Case of a String (C):

cCopy code

#include <stdio.h> #include <ctype.h> #include <string.h> void toUppercase(char* str) {    while (*str) {        *str = toupper(*str);        str++;    } } void toLowercase(char* str) {    while (*str) {        *str = tolower(*str);        str++;    } } int main() {    char str[] = "Hello, World!";        // Convert to uppercase    toUppercase(str);    printf("Uppercase string: %s\n", str);    // Convert to lowercase    toLowercase(str);    printf("Lowercase string: %s\n", str);    return 0; }

In both examples, we demonstrate converting the string "Hello, World!" to uppercase and then to lowercase.

For C++, the std::transform function is used with the ::toupper and ::tolower functions from the <cctype> header to convert each character of the std::string object to uppercase and lowercase, respectively.

For C, we define two functions, toUppercase and toLowercase, which use the toupper and tolower functions from the <ctype.h> header to convert each character of the character array to uppercase and lowercase, respectively.

The output of the program will be:

cCopy code

Uppercase string: HELLO, WORLD! Lowercase string: hello, world!

Both approaches will correctly change the case of the given string. Choose the one that suits your preference and the programming language you are using.

7. Strings

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support