Gary Ridgway
Gary Ridgway

Reputation: 69

Palindrome Checker in C

Where should I include toupper() in my code in order to make a palindrome such as Noon or NoOoON to say it is a palindrome rather than saying it is not a palindrome. I can't seem to figure it out. Thanks.

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

void reverse(char s[]){ 
    int c, i , j; 
    for (i = 0, j = strlen(s)-1; i < j; i++, j--) { 
        c = s[i]; 
        s[i] = s[j]; 
        s[j] = c; 
    } 
    return; 
} 

int main(){ 
    char a[20];
    char b[20];
    printf("Enter a string:\n");
    gets(a);
    strcpy(b,a); // copies string a to b 
    reverse(a); // reverses string b
    if(strcmp(a, b) == 0) { // compares if the original and reverse strings are the same 
        printf("The string is a Palindrome\n"); 
    } 
    else { 
        printf("The string is not a Palindrome\n"); 
    }    
    return 0; 
}

Upvotes: 0

Views: 277

Answers (2)

icedwater
icedwater

Reputation: 4887

If you want to use toupper() then you should apply it before you make a copy of the string and reverse it.

That is:

int main() { 
    char a[20];
    char b[20];
    int i = 0;
    printf("Enter a string:\n");
    gets(a);
    // make the change here
    for (i = 0; i < strlen(a); i++) {
        a[i] = toupper(a[i]);
    }
    strcpy(b, a);

If you convert the string to a single case later, then the copy will not be the same as the original, or you'd have to toupper() both.

Upvotes: 1

paddy
paddy

Reputation: 63471

In your case, you can just use _stricmp instead of strcmp.

Another way to approach this is to convert your string to a single case after it is input. eg

for (char *c = a; *c; c++) *c = toupper(*c);

Upvotes: 1

Related Questions