I have a string that may contain numbers as well as upper and lower case letters. I need to convert all the uppercase letters to lowercase and vice versa. How would one go about this?
Here's a way to do it without boost:
#include <string>
#include <algorithm>
#include <cctype>
#include <iostream>
char change_case (char c) {
if (std::isupper(c))
return std::tolower(c);
else
return std::toupper(c);
}
int main() {
std::string str;
str = "hEllo world";
std::transform(str.begin(), str.end(), str.begin(), change_case);
std::cout << str;
return 0;
}
Iterate the string and use isupper()
to determine if each character is uppercase or not. If it's uppercase, convert it to lowercase using tolower()
. If it's not uppercase, convert it to uppercase using toupper()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With