Java Data Type How to - Check if a string is palindrome








Question

We would like to know how to check if a string is palindrome.

Answer

public class Main {
  public static boolean isPalindrome(String stringToTest) {
    String workingCopy = removeJunk(stringToTest);
    String reversedCopy = reverse(workingCopy);
//from   ww w.j a va2  s .  co m
    return reversedCopy.equalsIgnoreCase(workingCopy);
  }
  static String removeJunk(String string) {
    int i, len = string.length();
    StringBuffer dest = new StringBuffer(len);
    char c;

    for (i = (len - 1); i >= 0; i--) {
      c = string.charAt(i);
      if (Character.isLetterOrDigit(c)) {
        dest.append(c);
      }
    }
    return dest.toString();
  }

  protected static String reverse(String string) {
    StringBuffer sb = new StringBuffer(string);
    return sb.reverse().toString();
  }
  public static void main(String[] args) {
    String string = "Madam, I'm Adam.";
    if (isPalindrome(string)) {
      System.out.println("yes");
    } else {
      System.out.println("no");
    }
  }
}