A Palindrome is defined as a string that is the same both forwards and backwards
ID: 3938355 • Letter: A
Question
A Palindrome is defined as a string that is the same both forwards and backwards. (For example, “bob” and “otto” are both palindromes). This program takes in a string and returns true if the string is a palindrome, false otherwise.
Q. Modify the method below (Don't change the basic format. Just modify) so that the detection ignores spaces. For example “no lemon, no melon” should now return true.
public class Palindrome {
public static void main(String[] args) {
System.out.print( " Enter string: ");
String str = IO. readString();
IO.outputBooleanAnswer (isTrue(str) );
}
public static boolean isTrue (String str) {
boolean isTrue = true;
str = str.toLowerCase() ;
for (int i=0; i<str.length(); i++) {
if ( str.charAt(i) != str.charAt(str.length( )-i-1) ) {
isTrue = false;
}
} return isTrue;
}
}
Explanation / Answer
Modify the isTrue functionas below
public static boolean isTrue (String str) {
boolean isTrue = true;
str=str.replaceAll("\s","");
str = str.toLowerCase();
for (int i=0; i<str.length(); i++) {
if ( str.charAt(i) != str.charAt(str.length( )-i-1) ) {
isTrue = false;
}
} return isTrue;
}
Explanation:
we are just removing the spaces and then checking if it's a palindrome or not.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.