Checking if a String is a Palindrome
A common beginner's problem is to check if a user's string is a palindrome. The first thing to notice that a a string is a palindrome if the string in reverse is the same as the normal string. So, we use the class String buffer to reverse the string s:
String a=new StringBuffer(s).reverse().toString();
and from here we check if a=s:
if(a.equals(s)){
return(true);
}
However, some palindrome checkers ignore spaces, upper and lower cases, commas, and etc. use replaceAll, and below is the final java code to check if a string is a palindrome:
public static boolean palindromeCheck(String s){
s=s.toLowerCase().trim().replaceAll(",","").replaceAll("'","").replaceAll(" ","");
if(a.equals(s)){
return(true);
}
return(false);
}
This will return true for s="Madam, I'm Adam" and "racecar" but not for "car"
String a=new StringBuffer(s).reverse().toString();
and from here we check if a=s:
if(a.equals(s)){
return(true);
}
However, some palindrome checkers ignore spaces, upper and lower cases, commas, and etc. use replaceAll, and below is the final java code to check if a string is a palindrome:
public static boolean palindromeCheck(String s){
s=s.toLowerCase().trim().replaceAll(",","").replaceAll("'","").replaceAll(" ","");
if(a.equals(s)){
return(true);
}
return(false);
}
This will return true for s="Madam, I'm Adam" and "racecar" but not for "car"
Provided by website-hit-counters.com site. |