Toggle each character in a string in C++
Understanding Character Toggling
Character toggling means converting uppercase letters to lowercase and vice versa.
We will explore three different methods to toggle characters in a string using C++.
Method 1: Using a Loop
This method iterates through the string and toggles each character.
#include <iostream> #include <cctype> using namespace std; void toggle_case(string &str) { for (char &ch : str) { if (islower(ch)) ch = toupper(ch); else if (isupper(ch)) ch = tolower(ch); } } int main() { string str; cout << "Enter a string: "; getline(cin, str); toggle_case(str); cout << "Toggled string: " << str << endl; return 0; }
Output: hELLOwORLD
Method 2: Using Recursion
This method toggles characters recursively.
#include <iostream> #include <cctype> using namespace std; void toggle_recursive(string &str, int index) { if (index == str.length()) return; if (islower(str[index])) str[index] = toupper(str[index]); else if (isupper(str[index])) str[index] = tolower(str[index]); toggle_recursive(str, index + 1); } int main() { string str; cout << "Enter a string: "; getline(cin, str); toggle_recursive(str, 0); cout << "Toggled string: " << str << endl; return 0; }
Output: pROGRAMMING
Method 3: Using Bitwise Operations
This method toggles characters using bitwise XOR operation.
#include <iostream> using namespace std; void toggle_bitwise(string &str) { for (char &ch : str) { ch ^= 32; } } int main() { string str; cout << "Enter a string: "; getline(cin, str); toggle_bitwise(str); cout << "Toggled string: " << str << endl; return 0; }
Output: tOGGLEcASE