Search code examples
cpalindromestring.h

Check if a word is palindrome with string.h


I must do a program that tells me if a string is palindrome or not using the library string.h . I wrote the following code but the output is always "palindrome"

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

int main()
{
 char a[100],b[100]; 
 int i,k;  
 printf("Type the string \n");
 gets(a);
 k=strlen(a);
 for(i=0;i<strlen(a);i++)
 {
  a[i]=b[k]; 
  k--;                       
 }           //at the end of this code the string "b" should be the reverse of "a"
 k=strcmp(a,b);
 if (k!=0)   //here I check if a=b or not
 {printf("palindrome");}
 else
 {printf("not palindrome");}
 getch();
 return 0;
}

Example: When my input is "non" the output should be "palindrome", if the input is "ship" the output should be "not palindrome". Could anyone help me to find what is wrong?


Solution

  • I think it's the line

    a[i]=b[k];

    Doesn't this put the contents of b[k] (which you have not initialized) into a[i] (which you have populated with the get)? This overwrites the test value in a with blanks, (or whatever was in b's memory) Shouldn't you do the opposite?

    But better is not to do it at all - you can just compare the characters in place in the a array.

    k=strlen(a);
    for(i=0; i<k/2; i++)
       if(a[i] != a[k-i]) 
          return "Not Palindrome";
    return "Palindrome";