String index out of range in jva

One approach would be to strip the non alpha characters out of the string. Then check if the string is the same as itself reversed (while upper case):

public static boolean isPalindrome(String palindrome) {
    StringBuilder sanitisedString = new StringBuilder();
    for(char c : palindrome.toCharArray()) {
        if(Character.isLetter(c)) {
            sanitisedString.append(c);
        }
    }
    return sanitisedString.toString().toUpperCase().equals(sanitisedString.reverse().toString().toUpperCase());
}

Leave a Comment