How do I ignore punctuation marks and whitespace in java?

user1730357 picture user1730357 · Jan 17, 2013 · Viewed 28.4k times · Source
import java.util.Scanner;
public class Ex3 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Please input a word: ");
        String Line = keyboard.nextLine();
        boolean x = isReverse(Line);
        System.out.print("It is " + x + " that this word is a palindrome.");
    }
    public static boolean isReverse(String Line) {
        int length = Line.length();
        boolean x = true;
        String s = "";
        for (int i = 0; i < length; i++) {
            if (Line.charAt(i) != ' ') {
                s += Line.charAt(i);
            }
        }
        for (int i = 0; i < length; i++) {
            if (Line.charAt(i) != Line.charAt(length - 1 -i)) {
                x = false;
            }
        }
        return x;   
    }
}

What I am trying to do is make a program that takes a word or phrase as input and returns true or false depending on if it is a palindrome or not. In the program I am supposed to ignore whitespace and punctuation marks and make palindromes such as "A man, a plan, a canal, Panama." I think I have solved the whitespace problem, but can not figure out how to ignore all punctuation marks.

Answer

assylias picture assylias · Jan 17, 2013

You could use a regular expression to remove all the non-word characters from your string: \\W represents non-word characters

String s = "A man, a plan, a canal, Panama.";
String lettersOnly = s.replaceAll("[\\W]", "");
System.out.println("lettersOnly = " + lettersOnly);

outputs:

lettersOnly = AmanaplanacanalPanama

If you want to reduce the length of your code, you can also use StringBuilder#reverse to reverse the string:

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Please input a word: ");
    String line = keyboard.nextLine();

    String cleanLine = line.replaceAll("[\\W]", "");
    String reverse = new StringBuilder(cleanLine).reverse().toString();
    boolean isPalindrome = cleanLine.equals(reverse);

    System.out.print("It is " + isPalindrome + " that this word is a palindrome.");
}

EDIT

If you need to stick to the loop, you can simply check in your loop if the characters are letters:

public static boolean isReverse(String Line) {
    int length = Line.length();
    boolean x = true;
    String s = "";
    for (int i = 0; i < length; i++) {
        if ((Line.charAt(i) >= 'a' && Line.charAt(i) <= 'z')
          || (Line.charAt(i) >= 'A' && Line.charAt(i) <= 'Z')) {
            s += Line.charAt(i);
        }
    }

Note: you will have an issue with the case (A != a) - an easy fix is to first put all characters in lower case with String lowerCase = Line.toLowerCase();.