Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,167 questions

40,724 answers

573 users

How to check if a string is palindrome by ignoring non-alphanumeric characters in Java

1 Answer

0 votes
public class MyClass {
    public static boolean is_palindrome(String s) {
        String s1 = remove_non_alphanumeric(s);
        String s2 = new StringBuilder(s1).reverse().toString();
        
        return s2.equals(s1);    
    }
    public static String remove_non_alphanumeric(String s) {
        StringBuilder sb = new StringBuilder();
        
        for (int i = 0; i < s.length(); i++) {
            if (Character.isLetterOrDigit(s.charAt(i))) {          
                sb.append(s.charAt(i));
            }
        }
        return sb.toString();
    }
    public static void main(String args[]) {
        System.out.println(is_palindrome("abcdcba"));
        System.out.println(is_palindrome("abc1221cba"));
        System.out.println(is_palindrome("!ab@c12$21c*(ba"));
    }
}


/*
run:

true
true
true

*/

 





answered Aug 3, 2019 by avibootz

Related questions

...