# Thread: palindrome problem

1. Member
Join Date
Oct 2009
Location
Denmark
Posts
10
Rep Power
0

## 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

2. Senior Member
Join Date
Aug 2009
Posts
2,388
Rep Power
10
What have you tried in the week that you have been struggling with it?

3. Member
Join Date
Oct 2009
Location
Denmark
Posts
10
Rep Power
0
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)

4. Moderator
Join Date
Apr 2009
Posts
13,067
Rep Power
23
Show us the loop you've written that doesn't work, and tell us in what way it doesn't work.

5. Senior Member
Join Date
Jun 2008
Posts
339
Rep Power
9
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.

6. 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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•