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 <stdio.h>
#include <ctype.h>
void toggle_case(char *str) {
for (int i = 0; str[i] != '\0'; i++) {
if (islower(str[i]))
str[i] = toupper(str[i]);
else if (isupper(str[i]))
str[i] = tolower(str[i]);
}
}
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
toggle_case(str);
printf("Toggled string: %s\n", str);
return 0;
}
Output: hELLOwORLD
Method 2: Using Recursion
This method toggles characters recursively.
#include <stdio.h>
#include <ctype.h>
void toggle_recursive(char *str, int index) {
if (str[index] == '\0') 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() {
char str[100];
printf("Enter a string: ");
gets(str);
toggle_recursive(str, 0);
printf("Toggled string: %s\n", str);
return 0;
}
Output: pROGRAMMING
Method 3: Using Bitwise Operations
This method toggles characters using bitwise XOR operation.
#include <stdio.h>
void toggle_bitwise(char *str) {
for (int i = 0; str[i] != '\0'; i++) {
str[i] ^= 32;
}
}
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
toggle_bitwise(str);
printf("Toggled string: %s\n", str);
return 0;
}
Output: tOGGLEcASE