trim method-

ignoring space and punctuation

Page 1 of 1

2 Replies - 1694 Views - Last Post: 28 March 2010 - 04:50 PM Rate Topic: -----

#1 Guest_guess2*


Reputation:

trim method-

Posted 28 March 2010 - 04:41 PM

I am trying to get a palindrome which ignores spaces; i have used trim method as it removes the spaces.But my program doesn't produce the result.Also, could you give me a hint of how to ignore the punctuation as well.

public class PalindromeTester {

    public static void main(String[] args) {
        String str;
        String another = "y";
        int left;
        int right;

        Scanner scan = new Scanner(System.in);

        while (another.equalsIgnoreCase("y")) {

            System.out.println("Enter a potential palindrome:");
            str = scan.nextLine();
            str = str.trim();   // this is suppose to trim the spaces but its not working.
            str = str.toLowerCase();
            left = 0;
            right = str.length() - 1;



            while (str.charAt(left) == str.charAt(right) && left < right) {
                left++;
                right--;
            }
            System.out.println("");

            if (left < right) {
               System.out.println("That string is NOT a palindrome.");
            } else {
                System.out.println("That string Is a palindrome.");
        }
            System.out.println("");
            System.out.println("Test another palindrome(y/n)? ");
            another = scan.nextLine();
        }
    }
}



Is This A Good Question/Topic? 0

Replies To: trim method-

#2 zim1985  Icon User is offline

  • Grand Inquisitor
  • member icon

Reputation: 74
  • View blog
  • Posts: 568
  • Joined: 19-February 10

Re: trim method-

Posted 28 March 2010 - 04:48 PM

Ignore punctuation
for(int i = 0; i < str.length; i++)
{
    char ch = str.charAt(i);
    if(ch == ',' || ch == '.' || ch == '/')  // ETC
        continue;
}


Was This Post Helpful? 1
  • +
  • -

#3 erik.price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 485
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Re: trim method-

Posted 28 March 2010 - 04:50 PM

*
POPULAR

The trim method only strips off leading and trailing whitespace.

You could use the replaceAll method to remove all the whitespace from a String:
str = str.replaceAll("\\s+", "");


If you didn't know already, the \\s+ just means one or more whitespace chars

You could use the same method to remove punctuation. Just be mindful, because for example if you do str = str.replaceAll(".", "");, you'll end up with a blank String (a dot means everything but a newline). You would have to do this: str = str.replaceAll("\\.", "");

edit: almost forgot, this is much easier:
str = str.replaceAll("\\W+", "");


The \\W+ means to remove everything that's not a letter (space, punctuation, etc.)

This post has been edited by erik.price: 28 March 2010 - 04:53 PM

Was This Post Helpful? 6
  • +
  • -

Page 1 of 1