If you have any query feel free to chat us!
Happy Coding! Happy Learning!
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 thestd::string
object to uppercase and lowercase, respectively.For C, we define two functions,
toUppercase
andtoLowercase
, which use thetoupper
andtolower
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.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform