1

I'm trying to create a program that checks if a given array/string is a palindrome or not and its not working. The program just prints "0" on every given array, even on palindromes.

int main()
{

    char string[100]= {0};
    char stringReverse[100]= {0};

    int temp = 0;
    int firstLetter = 0;
    int lastLetter = 0;

    printf("Please enter a word or a sentence: ");
    fgets(string, 100, stdin);

    strcpy(stringReverse , string); // This function copies the scanned array to a new array called "stringReverse"

    firstLetter = 0;
    lastLetter = strlen(string) - 1;    //because in array, the last cell is NULL

    // This while reverses the array and insert it to a new array called "stringReverse"
    while(firstLetter < lastLetter)
    {
        temp = stringReverse[firstLetter];
        stringReverse[firstLetter] = stringReverse[lastLetter];

        stringReverse[lastLetter] = temp;

        firstLetter++;
        lastLetter--;
    }

    printf("%s    %s", stringReverse, string);

    if ( strcmp(stringReverse , string) == 0)
    {
        printf("1");
    }
    else
    {
        printf("0");
    }
} 
Madhav Datt
  • 1,065
  • 2
  • 10
  • 25
Shmuel
  • 57
  • 1
  • 1
  • 3

6 Answers6

6

Lets say we implement a simple fun to do that

int check_palindrome (const char *s) {
   int i,j;
   for (i=0,j=strlen(s)-1 ; i<j ; ++i, --j) {
      if (s[i] != s[j]) return 0; // Not palindrome
   }
   return 1; //Palindrome
}

I think this is far more simpler ;)

For the code posted in question: Be aware of fgets(). It stops in the first '\n' or EOF and keeps the '\n' character.

So if you give radar for ex, the result string will be "radar\n", which doesn't match with "\nradar"

hoo2
  • 515
  • 1
  • 3
  • 11
  • There is no simpler way to do it than this. It's all you need. Don't forget to write a function to check for leading/trailing whitespace and you should be fine. If you have trouble with that, C actually has a function called `isspace()` which takes a char (technically it takes an int but just give it a char) and returns a non-zero value if it is a whitespace char such as \n, \t, \v, or a space. Returns 0 otherwise. – James Jan 22 '16 at 19:04
2

The Problem:

Let's say you enter the string RACECAR as input for your program and press enter, this puts a newline character or a '\n' in your buffer stream and this is also read as part of your string by fgets, and so your program effectively ends up checking if RACECAR\n is a palindrome, which it is not.

The Solution:

After you initialize lastLetter to strlen(string) - 1 check if the last character in your string (or the character at the lastLetter index is the newline character (\n) and if so, decrease lastLetter by one so that your program checks if the rest of your string (RACECAR) is a palindrome.

lastLetter = strlen(string) - 1;    //because in array, the last cell is NULL

// Add these 2 lines to your code
// Checks if the last character of the string read by fgets is newline
if (string[lastLetter] == '\n')
    lastLetter--;
Madhav Datt
  • 1,065
  • 2
  • 10
  • 25
1

fgets adds a '\n' at the end. So if the user entered "aba", string contains "aba\n". reverseString contains "\naba".

So it doesn't match.

After the fgets, add this code

int l = strlen(string) - 1;
string[l] = 0;

This will strip out the '\n' at the end before copying it to reverseString.

That aside, you can do this whole program inplace without the need of a second buffer or strcpy or strlen calls.

user93353
  • 13,733
  • 8
  • 60
  • 122
  • Detail: `fgets()` does not _add_ `'\n'`. It simples saves it like all other input characters. If user input was only 3 characters: `"aba"`, no key, and then `stdin` was closed, input would only be `'a'`, `'b'`, `'c'`. `fgets()` does _add_ the terminating null character. To safely remove the potential `'\n'`, consider http://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input/27729970#27729970 – chux - Reinstate Monica Jan 22 '16 at 17:18
1

You have several issues in your code:

  • first you forgot the last closing brace };
  • then you forgot to remove the trailing \n (or maybe also \r under Windows) in string;
  • you don't need to revert the string into a new string; a one-pass check is enough:

Here is a working code:

#include <stdio.h>
#include <string.h>
int main()
{

    char string[100]= {0};

    int temp = 0;
    int firstLetter = 0;
    int lastLetter = 0;

    printf("Please enter a word or a sentence: ");
    fgets(string, 100, stdin);

    firstLetter = 0;
    lastLetter = strlen(string) - 1;    //because in array, the last cell is NULL
    while ((string[lastLetter]=='\n')||(string[lastLetter]=='\r')) {
        lastLetter--;
    }

    // This while reverses the array and insert it to a new array called "stringReverse"
    temp = 1;
    while(firstLetter < lastLetter)
    {
        if (string[firstLetter] != string[lastLetter]) {
            temp = 0;
            break;
        }

        firstLetter++;
        lastLetter--;
    }

    if ( temp )
    {
        printf("1");
    }
    else
    {
        printf("0");
    }
}
Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46
  • Note: `fgets(string, ...); int lastLetter = strlen(string) - 1; while ((string[lastLetter]...` is a hacker exploit. It is fairly easy to have the first character of `string` to be `'\0'` and then `string[-1]` is UB. Consider http://stackoverflow.com/q/2693776/2410359 – chux - Reinstate Monica Jan 22 '16 at 17:24
  • @chux Yes, but this is only an adaptation of the post of the original poster; I merely changed the lines having issues. Of course other things could be improved. – Thomas Baruchel Jan 22 '16 at 20:25
0

You can do it by this simpleway also.

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

int main()
{
    char string[10], revString[10];
    printf("Enter string for reversing it...\n");
    scanf("%s", string);

    int stringLength = strlen(string);

    for(int i = 0; string[i] != '\0'; i++, stringLength--)
    {
    revString[i] = string[stringLength - 1];
    }

    if(strcmp(string,  revString) == 0)
         printf("Given string is pelindrom\n");
    else
         printf("Given string is not pelindrom\n");
}
Sagar Patel
  • 864
  • 1
  • 11
  • 22
0
#include<stdio.h>
#include<string.h>`enter code here`
void fun(char *a);
 int main () 
 {    
     
      char p[100];
      char *s=p;
      
     printf("enter the string");
     scanf("%[^\n]",s);
     fun(s);
   
     
 }

void fun(char *a)
 { 
 
        
      if(*a && *a!='\n')
     {
      fun(a+1);
       
          putchar(*a);
       
      }
}

// use this approach better time complexity and easier work hope this helps

shadowfax
  • 1
  • 1