Results 1 to 3 of 3
  1. #1
    counterfox is offline Member
    Join Date
    Mar 2009
    Posts
    45
    Rep Power
    0

    Default checking a palindrome sentance

    Hi got a method to check if a string is a palindrome but not including spaces or punctuation for example:

    "a,s dfdsa"

    would be a palindrome. What I'm confused with is there a decent way in java to get rid of these spaces/punctuation? or is there something else that needs to be done?

    The code I got so far would only work on something like "asdfdsa". (A string with no spaces or punctuation.
    Heres my current code:

    int strLeft = 0;
    int strRight = str.length() -1;

    while (strLeft < strRight) {
    if (str.charAt(strLeft) != str.charAt(strRight)) {
    return false;
    }
    strLeft++;
    strRight--;
    }

    return true;


    Thanks in advance

  2. #2
    eRaaaa is online now Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    5

    Default

    replace all spaces or punctuations in the string in your first/second line.
    e.g. with regex -> str = str.replaceAll("\\W|_", "");
    that will replace all non-word characters (all those not matching [a-zA-Z or 0-9])

    other tip: your palindrom test fails if you have upper case letters mixed with lower case letters in your string...do you like that? if not, you could use e.g. Character.toLowerCase(str.charAt(strLeft)) != ....

  3. #3
    counterfox is offline Member
    Join Date
    Mar 2009
    Posts
    45
    Rep Power
    0

    Default

    Thanks I forgot to consider the lower/uppercase would cause a problem. Got the method to work now, thanks for the help.

Similar Threads

  1. Test for Palindrome
    By arson09 in forum New To Java
    Replies: 11
    Last Post: 09-29-2010, 07:57 PM
  2. Palindrome
    By pinkdreammsss in forum Java Applets
    Replies: 8
    Last Post: 05-04-2010, 03:59 PM
  3. HELP...Palindrome
    By d7o0om in forum New To Java
    Replies: 12
    Last Post: 11-13-2009, 03:32 AM
  4. palindrome problem
    By Blaedel in forum New To Java
    Replies: 5
    Last Post: 10-03-2009, 12:52 AM
  5. Palindrome Test
    By Ada in forum New To Java
    Replies: 1
    Last Post: 05-26-2007, 01:36 PM

Posting Permissions

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