strcmp usage

  • Follow


I'm writing a function to check if an input sentence is a palindrome. 
So the input would have at least one word. Punctuation and space are to be disregarded. An example would be:

input='mom''m   m''mom           mom''m m''mom'
output=true (or 1, as long as it's logical)

input='my car''s engine is good'
output=false (or 0, as long as it's logical)

This is what I've got so far:
s=inputSentence
c=strread(s,'%s');  % trying to organize the sentence into something that can be operated on
strcmp(c(1),c(end:-1:1)); %trying to compare, but not sure how to use this??

The last sentence with strcmp is where i screw up. Not sure about the strread(s, '%s') either. Any help appreciated. Thanks. 
0
Reply Raymond 9/16/2010 3:51:04 AM

"Raymond " <atlantaswagsurfers3@yahoo.com> wrote in message <i6s478$d9e$1@fred.mathworks.com>...
> I'm writing a function to check if an input sentence is a palindrome. 
> So the input would have at least one word. Punctuation and space are to be disregarded. An example would be:
> 
> input='mom''m   m''mom           mom''m m''mom'
> output=true (or 1, as long as it's logical)
> 
> input='my car''s engine is good'
> output=false (or 0, as long as it's logical)
> 
> This is what I've got so far:
> s=inputSentence
> c=strread(s,'%s');  % trying to organize the sentence into something that can be operated on
> strcmp(c(1),c(end:-1:1)); %trying to compare, but not sure how to use this??
> 
> The last sentence with strcmp is where i screw up. Not sure about the strread(s, '%s') either. Any help appreciated. Thanks. 

if by palindrome you mean a word-unit palindrome (WOMEN UNDERSTAND MEN; FEW MEN UNDERSTAND WOMEN) then you're almost there

strcmp(c(1),c(end:-1:1))   is comparing the first word (c(1)) with each of the other words, in reverse order.

i think you need strcmp(c(1:end),c(end:-1:1)).   This will compare each word of the sentence with the word from the reversed sentence.  if they're all equal, it would be a word-unit palindrome.

on the other hand, a standard palindrome is much easier (Madam I'm Adam) - just toss out the spaces and punctuation, then test whether all(s==s(end:-1:1))

Ross
0
Reply Ross 9/16/2010 5:29:06 AM


1 Replies
278 Views

(page loaded in 0.159 seconds)


Reply: