• C


I have managed to code a function to check if a word is a palindrome..
However, how to check if a sentence with many words is a palindrome?

Example of a palindrome sentence are these:
1. He is the the is he.
2. hello world hello.

Can give me hints on how to figure this?
Who is Participating?
stefan73Connect With a Mentor Commented:
Hi Mysidia,
> Consider using a recursive call.
Yes, that would be a solution "by the book". As this problem smells like homework, that's probably the way to do it :-)

Basically, like this:

   backposition = length of word - position
   if(backposition <= position)
      return true

   else if word[position]  != word[backposition]
      return false

      return is_palidrome(word, position +1 )


you mean when the words are taken as a whole?
i.e  He is the the is he  is obviously not a palindrome if you comsider letters  and not words

anyway a crude way to check if a sentence is a palindrome ( by your definition)
would be to

store the words in an array  

char array1[MaxWords] [Maxlength]  ;    where the MaxWords and Maxlength are constants chosen to your need

after you have filled the array with the words in the sentence you
can read it backwards and put the words in another array

now if both the arrays match then the sentence is a palindrome.


This is This

your array now contains

A1[0] = This
A1[1]  = is
A1[2]  = This

read it in reverse and put in array2

A2[0] = This
A2[1]  = is
A2[2]  = This

and since they are same , it is a palindrome

similarly for

This is dog
we have

A1[0] = This
A1[1]  = is
A1[2]  = dog

and the reverse is

A2[0] = dog
A2[1]  = is
A2[2]  = This
so since A1 is not equal to A2  this is not a palindrome

ee_guestAuthor Commented:
the number of words and the number of letters per word is not known.
that's the problem.
Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

you can use the strtok() function

       strtok, strtok_r - extract tokens from strings

       #include <string.h>

       char *strtok(char *s, const char *delim);

       char *strtok_r(char *s, const char *delim, char **ptrptr);

       A  `token'  is a nonempty string of characters not occurring in the string delim, followed by \0 or by a character occur-
       ring in delim.

       The strtok() function can be used to parse the string s into tokens. The first call to strtok()  should  have  s  as  its
       first  argument.  Subsequent  calls  should  have the first argument set to NULL. Each call returns a pointer to the next
       token, or NULL when no more tokens are found.

       If a token ends with a delimiter, this delimiting character is overwritten with a \0 and a pointer to the next  character
       is saved for the next call to strtok().  The delimiter string delim may be different for each call.

       The  strtok_r()  function  is a reentrant version of the strtok() function, which instead of using its own static buffer,
       requires a pointer to a user allocated char*. This pointer, the ptrptr parameter, must be the same while parsing the same
he is the the is he

count how many words u have in ur sence ( by looping thourgh the whole string and using SPACE delimiter)

-tokenzise ur sentence into arrary of string

char * array[n]  -> n is the number that u obtain from 1st step
using strtok(char* str, char* delimiter)

for example:

char * s="he is the the is he"
strtok(s," ') will be "he"
strtok(NULL," ") will be "is"
strtok(NULL," ") will be "the"

( remember u should work on a copy of ur sentence string cuz strtok gonna change ur input string)

first string with last string: array[0] with array[n-1-0]   : array is array of string u got from step 2, and n is number of words in ur sentence (step 1)
second with second last: array[1] with array[n-1-1]
array[m] with array[n-1-m]

to compare to 2 string, use function strcmp(char*,char*) -> return 0 if they are equals.

-> for 3rd step, u can use for loop.

Hope it will help.

to count a number of word in a sentence string, use this function

int countToken(char* s)
  int count;
    return 0;

  /* first one */
  strtok(s," ');

  /* keep tokenize until it returns a NULL */
  while(strtok(NULL," ")!=NULL)
     count++; /* increase the number of words */
  return count;

remember: use a copy of ur original string cuz strtok gonna change ur string. For example:

orginal string="This is an example"
Strtok function will put '\0' into spaces between ur orginal string:

This is the function which takes as input the string and returns the result as 1 if the input is a palindrome in words and 0 otherwise.

int is_palindrome_word(char* s) {
      char str[100];
      char* token[10] ;
      int no_of_tokens = 0, i ;
      strcpy(str, s) ;
      token[0] = strtok(str, " ");
      while((token[no_of_tokens] = strtok(NULL, " ")) != NULL)
      printf("Total tokens = %d\n", no_of_tokens);
      for(i = 0 ; i < (no_of_tokens/2); i++) {
            if ( strcmp(token[i], token[no_of_tokens-i-1] ) )
                  return 0 ;
      return 1 ;

Do get beck in case of any problem.

ee_guestAuthor Commented:
to all..
the string to be checked has got unknown length and so using fixed array size is not feasible here..
Consider using a recursive call.  Peel away the first and last word, compare them,
and check the inner piece at each succesive call.
lebuihungConnect With a Mentor Commented:
hi ee_guest,

basically, we dont have to know the length of string -> cuz all i do is try to find terminated character '\0' or use strlen function to get the length of this string.
No recursion needed: keep two pointers, one to beginning of sentence, one to end. Similar to Mysidia's solution, compare first/last words, move end pointer forward one word, move front pointer one word. Stop when end is in front of start pointer. This way you could test a sentence of thousands of words without crashing.

Also, it might help to write a wordcmp() function that uses space character as terminator.
aasiaConnect With a Mentor Commented:
int getTokenCount(char *input)
      int wordCount = 0;
      if (strlen(input) == 0)
            return wordCount;
      char *tokenInput = strtok(input, " ");
      while (tokenInput != NULL)
            tokenInput = strtok(NULL, " ");
      return ((wordCount / 2) + (wordCount % 2));

char **getTokens(char *input, int tokCount)
      if (strlen(input) == 0)
            return NULL;
      int wordIdx = 0;
      char *tokenInput = strtok(input, " ");
      char **tokens = (char **)malloc(tokCount * sizeof(char **));
      while ((tokenInput != NULL) && (wordIdx < tokCount))
            tokens[wordIdx] = (char *) malloc((strlen(tokenInput) + 1) * sizeof(char));
            strcpy(tokens[wordIdx++], tokenInput);
            tokenInput = strtok(NULL, " ");

      return tokens;

bool isPalin(char *input)
      bool retVal = true;
      if (strlen(input) == 0)
            return retVal;
      char *tempInp = strdup(input);

      int tokCount = getTokenCount(tempInp);


      tempInp = strdup(input);

      char **inputTokens = getTokens(tempInp, tokCount);


      char *revInput = strdup(input);
      char **outputTokens = getTokens(revInput, tokCount);
      for (int idx = 0; (idx < tokCount) && retVal; idx++)
            if (strcmpi(inputTokens[idx], strrev(outputTokens[idx])) != 0)
                  retVal = false;
      return retVal;
BTW: my solution suggestion is tail-recursive. A good optimizer should be able to convert it into a loop, so you don't have to worry about crashing because of stack usage.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.