# palindrome problem

• 10-01-2009, 08:00 PM
Blaedel
palindrome problem
Hi

I'm trying to solve a evedently quite simple problem... However somehow I can't seem to get it right.

What i wan't the program to do is to recognise a palindrome words or sentences (eg, hannah which is spelt the same even if you read from last letter to the first, and "Fall leaves after leaves fall") using only basic programming such as loops, string object methods (I believe they are called), such as s.substring(n, n+1); s.replace(E, X); etc., and of course conditions (if, else).

I've been struggling with this problem a week now and getting pretty tired of it...

A line by line explanation will be much appreciated but not of course not a precondition to help me :)

thanks a lot
/Martin
• 10-01-2009, 08:05 PM
r035198x
What have you tried in the week that you have been struggling with it?
• 10-01-2009, 08:34 PM
Blaedel
Different things, but the thing I keep returning to (probably not wisely) is this.

to make a loop that take the last letter of the sentence s1 with the substring method.

s2 = s1.substring(a-1, a);

where a = s2.lenght()

in a loop. where a is suppose to count down.

after that s2 = s2.replace(a-1, "")

to cut the word

and the add it to my new variable

s3 = s3 + s2;

... After this I'll of course compare the new word or sentence with the original using s4.equals.s2 but I don't think that will cause any problems.

But that counting down procedure does not work. When I can make that loop work I can solve the entire problem. And I seem to be lacking ideas to solve it in another way (though I have tried more, let's say exotic variant with no luck)
• 10-02-2009, 10:25 AM
Tolls
Show us the loop you've written that doesn't work, and tell us in what way it doesn't work.
• 10-02-2009, 12:11 PM
dlorde
Just a thought as I pass through - what about comparing each character, starting at each end and working to the middle? Or taking the second half of the string, reversing it, and comparing to the first half? You just have to make sure you ignore the middle character for odd-length strings.
• 10-03-2009, 01:52 AM
Mr.Beans
I had that problem in one of my classes last year.

I remember that I found it much easier to get an array of chars which represented the string. I iterated through them to check if the string was indeed a palindrome.

You can use String.toCharArray() to get an array of chars.