C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Non-letter chars: The two nested while loops, that test for Character.isLetter, advance past non-letter chars—this skips spaces.
ToLowerCase: We invoke Character.toLowerCase to convert uppercase letters to lowercase ones. So "X" and "x" are equal.
Main: Here we test an array of Strings for palindromes. We write our results to console.
ArrayJava program that checks for palindromes
public class Program {
public static boolean isPalindrome(String value) {
// Scan towards the middle, adjusting the start and end indexes.
int min = 0;
int max = value.length() - 1;
while (true) {
if (min > max) {
return true;
}
// Move forward past non-letter chars at the start.
while (!Character.isLetter(value.charAt(min))) {
min++;
}
// Move backward past non-letter chars at the end.
while (!Character.isLetter(value.charAt(max))) {
max--;
}
char a = Character.toLowerCase(value.charAt(min));
char b = Character.toLowerCase(value.charAt(max));
// If letters are not equal, this is not a palindrome.
if (a != b) {
return false;
}
// Advance towards center.
min++;
max--;
}
}
public static void main(String[] args) {
// Some example lines.
String[] lines = { "civic", "A man, a plan, a canal: Panama.",
"A Toyota. Race fast, safe car. A Toyota.",
"Cigar? Toss it in a can. It is so tragic.",
"Dammit, I'm mad!", "Delia saw I was ailed.",
"Desserts, I stressed!", "Draw, O coward!", "Lepers repel.",
"Live not on evil.", "Lonely Tylenol.",
"Murder for a jar of red rum.", "Never odd or even.",
"No lemon, no melon.", "Senile felines.", "So many dynamos!",
"Step on no pets.", "Was it a car or a cat I saw?",
"The Dev Codes is not a palindrome.",
"Why are you reading this?", "This article is not useful." };
// Test each line to see if it is a palindrome.
for (String line : lines) {
if (isPalindrome(line)) {
System.out.println("Palindrome: " + line);
} else {
System.out.println("Not palindrome: " + line);
}
}
}
}
Output
Palindrome: civic
Palindrome: A man, a plan, a canal: Panama.
Palindrome: A Toyota. Race fast, safe car. A Toyota.
Palindrome: Cigar? Toss it in a can. It is so tragic.
Palindrome: Dammit, I'm mad!
Palindrome: Delia saw I was ailed.
Palindrome: Desserts, I stressed!
Palindrome: Draw, O coward!
Palindrome: Lepers repel.
Palindrome: Live not on evil.
Palindrome: Lonely Tylenol.
Palindrome: Murder for a jar of red rum.
Palindrome: Never odd or even.
Palindrome: No lemon, no melon.
Palindrome: Senile felines.
Palindrome: So many dynamos!
Palindrome: Step on no pets.
Palindrome: Was it a car or a cat I saw?
Not palindrome: The Dev Codes is not a palindrome.
Not palindrome: Why are you reading this?
Not palindrome: This article is not useful.
So: It is possible to preprocess a string, with Replace or a regular expression, to eliminate these characters.
ReplaceHowever: For performance, and clarity, it is better to skip past these characters within the isPalindrome method.