String Exercises
Write a C program to toggle case of each characters of a string using loop. How to change case of each characters of a string in C programming. Program to swap case of each characters in a string using loop in C. Logic to reverse the case of each character in a given string in C program.
Required knowledge
Basic C programming, C for loop, Array, Pointer, functions, Strings
Logic to toggle case of a given string
Below is the step by step descriptive logic to toggle or reverse case of a given string.
- Input string from user, store it in some variable say str.
- Run a loop from start of the string to the end. Say the loop structure is while(str[i] != '\0').
- Inside the loop for each lowercase characters convert it to uppercase and vice versa.
Program to toggle case of a string
/** * C program to toggle case of each character in a string */ #include <stdio.h> #define MAX_SIZE 100 // Maximum string size /* Toggle case function declaration */ void toggleCase(char * str); int main() { char str[MAX_SIZE]; /* Input string from user */ printf("Enter any string: "); gets(str); printf("String before toggling case: %s", str); toggleCase(str); printf("String after toggling case: %s", str); return 0; } /** * Toggle case of each character in given string */ void toggleCase(char * str) { int i = 0; while(str[i] != '\0') { if(str[i]>='a' && str[i]<='z') { str[i] = str[i] - 32; } else if(str[i]>='A' && str[i]<='Z') { str[i] = str[i] + 32; } i++; } }
You can also use pointers in the toggleCase() function, which is pretty much straightforward and optimal. Let us re-write the above toggleCase() function using pointers.
void toggleCase(char * str) { while(*str) { if(*str >= 'a' && *str <= 'z') *str = *str - 32; else if(*str >= 'A' && *str <= 'Z') *str = *str + 32; str++; } }