cstringpalindromeletters

Palindrome C program convert capital letters to small letters


At school Im working on a palindrome C program. I'm almost done, but I would like my program to mark both 'Anna' and 'anna' as a palindrome. I tried some stuff out but nothing really worked. My code :

#include <stdio.h>
#include <string.h>

int main() {
    char palindroom[50],a;
    int lengte, i;
    int woord = 0;

    printf("This program checks if your word is a palindrome.\n");
    printf("Enter your word:\t");
    scanf("%s", palindroom);

    lengte = strlen(palindroom);

    for (i = 0; i < lengte; i++) {
        if (palindroom[i] != palindroom[lengte - i - 1]) {
            woord = 1;
            break;
        }
    }

    if (woord) {
        printf("Unfortunately, %s is not palindrome\n\n", palindroom);
    }
    else {
            printf("%s is a palindrome!\n\n", palindroom);
    }
    getchar();
    return 0;
}

I've seen some people using tolower from ctype.h but I'd like to avoid that.

So my question is : how do I convert all uppers to lowers in a string?

[ps. some words I may code might seem odd, but that's Dutch. Just erase an o and you'll understand]

Thanks.


Solution

  • the difference between uppercase and lowercase in ASCII table is 32 so you can add 32 if an uppercase letter is in the input to convert it to lowercase ( http://www.asciitable.com/ ) :

    if ((currentletter > 64) && (currentletter < 91))
        {
            char newletter;
            newletter = currentletter + 32;
            str[i] = newletter;
        }
        else
        {
            str[i] = currentletter;
        }
    

    modified program :

    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char palindroom[50],a;
        int lengte, i;
        int woord = 0;
    
        printf("This program checks if your word is a palindrome.\n");
        printf("Enter your word:\t");
        scanf("%s", palindroom);
    
        lengte = strlen(palindroom);
    
        for (i = 0; i < lengte; i++) 
            {
                 if (palindroom[i] > 64 && palindroom[i] < 91)
                        { 
                          palindroom[i] = palindroom[i] + 32;
                        }         
    
            if (palindroom[i] != palindroom[lengte - i - 1]) {
                woord = 1;
                break;
            }
        }
    
        if (woord) {
            printf("Unfortunately, %s is not palindrome\n\n", palindroom);
        }
        else {
                printf("%s is a palindrome!\n\n", palindroom);
        }
        getchar();
        return 0;
    }
    

    65 is the decimal representation of A in the ASCII table, 90 is the decimal representation of Z while a is 97 ( = 65 +32 ) and z is 122 ( = 90 +32 )