C Program to toggle the case of every character in the input string

Every character in C programming is stored as ASCII value. The value of ‘A’ and ‘a’ in ASCII are 65 and 97 respectively. Since there is a difference of 32 between these two numbers one need to subtract 32 from the lowercase letter to convert it into uppercase, Similarly one has to add 32 to convert a uppercase letter to lowercase letter. These two conversions can also be achieved logically using ‘A’-‘a’ and ‘a’-‘A’ expressions. This program checks every character of the string and then toggles the case of every character using above mentioned logical expressions.

C Program to toggle the case of every character

Source code:

int main()
    char istr[128]; /* input buffer */
    char tstr[128]; /* translated string here */
    int i;
    int slen; /* string length */
        printf("Enter a string...   :");
        gets(istr);                                    // Step 1 
        if((slen=strlen(istr))==0)                     // Step 2
            break; /* terminate */
        strcpy(tstr,istr); /* make a copy */           // Step 3
        i = 0;
        while(i < slen) /* translate loop */             // Step 4
            if(tstr[i] >= 'A' && tstr[i] <= 'Z')           // Step 4(i)
                /* upper case */
                tstr[i] += 'a'-'A';
            else if(tstr[i] >= 'a' && tstr[i] <= 'z')       // Step 4(ii)
                /* lower case */
                tstr[i] += 'A'-'a';
            i++; /* to next character */
        printf("Original string = %s\n",istr);                 
        printf("Transformed string = %s\n",tstr);                // Step 5
    return 0;


Sample test cases:

1.  Enter a string...   : The TrEe
    Original string = The TrEe
    Transformed string = tHE tReE

2.  Enter a string...   : HeLLo
    Original string = HeLLo
    Transformed string = hEllO


Step 1: The string is read from the user using gets() function.
Step 2: If string is empty then no need to toggle the case. So before procedding, the string length is checked and if we found it to be zero then we exit from the program.
Step 3: The copy of given string is taken into ‘tstr’
Step 4: Every character in string is checked against two cases
Step 4(i): If character is uppercase then it is converted to lowercase by using ‘a’-‘A’ expression.
Step 4(ii) : If character is lowercase then it is converted to uppercase by using ‘A’-‘a’ expression.
Step 5: The converted string is printed on output screen using printf() function.

This is how you can toggle the case of every character in a given input string.

Explore C Programs: C Programs
More Content:ASCII