How to print the palindrome words in a string with Java

2 Answers

0 votes
public class MyClass {
    public static boolean isPalindrom(String word) {
        word = word.toLowerCase();
         
        for (int i = 0; i < word.length() / 2; i++) {
            if (word.charAt(i) != word.charAt(word.length() - (i + 1))) {
                return false;
            }
        }
         
        return true;
    }
    public static void main(String args[]) {
        String string = "java madam c++ civic java pytyp dart";
         
        String[] words = string.split(" ");
    
        for (String w : words) {
            if (isPalindrom(w)) {
                System.out.println(w);    
            }
        }
    }
}
  
  
  
 
/*
run:
  
madam
civic
pytyp
  
*/

 

 



answered Dec 29, 2023 by avibootz
edited Dec 29, 2023 by avibootz
0 votes
public class MyClass {
    public static boolean isPalindrom(String word) {
        return word.equals(new StringBuilder(word).reverse().toString());
    }
    public static void main(String args[]) {
        String string = "java madam c++ civic java pytyp dart";
         
        String[] words = string.split(" ");
    
        for (String w : words) {
            if (isPalindrom(w)) {
                System.out.println(w);    
            }
        }
    }
}
  
  
  
 
/*
run:
  
madam
civic
pytyp
  
*/

 



answered Dec 29, 2023 by avibootz

Related questions

...