hi, i have to create this program that reads in a string and then determines if it is a palindrome or not (eg. dad, radar). but it has to ignore special characters, operators(*,+,& etc.). i have the program all working but it doesn't ignore the special characters. i thought i made the program ignore it by using the if ((letter >= 'a') && (letter <= 'z')) part in my code, thanks in advance for any help
public class Palindrome { public static void main(String[] args) { System.out.println("Please enter a sentence: "); String str = SavitchIn.readLine();
if (palindrometester(str)) System.out.println("The input is a palindrome.");
else System.out.println("The input is not a palindrome."); }
I just wrote a method which will remove all the special chars from your String. Why don't you pass your string through that and then call the palindrometester method. So you don't have to do any of the special char checking in there...
publicstatic String removeSpecial(String pala){
String buffer = "";
char tempChar;
for (int i = 0; i < pala.length(); ++i){
tempChar = pala.charAt(i);
if ((tempChar < 'a') || (tempChar > 'z'))
continue;
buffer += tempChar;
}
return buffer;
}
Simply comparing against the range 'a'-'z' will omit uppercase letters, which may not be what you want. Why not use java.lang.Character.isLetter() instead?