I am trying to create a method called "palindrome" that receives a String and returns a boolean value of true if the String is a Palindrome and false if it is not. A word is a palindrome if it reads the same forwards and backward. For example, the word level is a palindrome.
For Example as palindromes by considering the text that is obtained by removing all spaces and punctuation marks and converting all letters to their lower-case form:
Madam, I'm Adam ==> madamimadam
A man, a plan, a canal: Panama ==> amanaplanacanalpanama
I tried to work on my code that I used replaceAll();
and output as the last line of replacing all.
public static String palindrome(String n){
char[] input = n.toCharArray();
//for(int i=0; i<input.length; i++){ //looping reversing using input as in length minus 1 from end to start and counting using increment
n.toLowerCase();
String noSpaces = n.replaceAll(" ", ""); //I used this to get string
String remove = noSpaces.replaceAll(",","");
String remove2 = remove.replaceAll(".","");
String remove3 = remove2.replaceAll(":","");
String remove4 = remove3.replaceAll("!", "");
System.out.print(remove4);
//return n;
//}
return n;
}
Compiler/Output:
Input: Madam, I'm Adam
Output:
The output is showing nothing anything? What am I doing wrong?
The problem is the dot essentially matches any character any number of times. So if you put remove.replaceAll(".","")
all the characters gets replaced with nothing. You should escape the dot to specify the actual dot. Hope this helps.
n = n.toLowerCase();//you should assign the result to get lowercase characters
String noSpaces = n.replaceAll(" ", ""); //I used this to get string
String remove = noSpaces.replaceAll(",","");
String remove2 = remove.replaceAll("\\.","");
String remove3 = remove2.replaceAll(":","");
String remove4 = remove3.replaceAll("!", "");
String remove5 = remove2.replaceAll("\'","");//you should also escape apostrophe
System.out.print(remove5);