public class PalindromeTester {
public static void main(String[] args) {
String str;
String another = "y";
int left;
int right;
Scanner scan = new Scanner(System.in);
while (another.equalsIgnoreCase("y")) {
System.out.println("Enter a potential palindrome:");
str = scan.nextLine();
str = str.trim(); // this is suppose to trim the spaces but its not working.
str = str.toLowerCase();
left = 0;
right = str.length() - 1;
while (str.charAt(left) == str.charAt(right) && left < right) {
left++;
right--;
}
System.out.println("");
if (left < right) {
System.out.println("That string is NOT a palindrome.");
} else {
System.out.println("That string Is a palindrome.");
}
System.out.println("");
System.out.println("Test another palindrome(y/n)? ");
another = scan.nextLine();
}
}
}
trim method-ignoring space and punctuation
Page 1 of 1
2 Replies - 1066 Views - Last Post: 28 March 2010 - 04:50 PM
#1 Guest_guess2*
trim method-
Posted 28 March 2010 - 04:41 PM
I am trying to get a palindrome which ignores spaces; i have used trim method as it removes the spaces.But my program doesn't produce the result.Also, could you give me a hint of how to ignore the punctuation as well.
Replies To: trim method-
#2
Re: trim method-
Posted 28 March 2010 - 04:48 PM
Ignore punctuation
for(int i = 0; i < str.length; i++)
{
char ch = str.charAt(i);
if(ch == ',' || ch == '.' || ch == '/') // ETC
continue;
}
#3
Re: trim method-
Posted 28 March 2010 - 04:50 PM

POPULAR
The trim method only strips off leading and trailing whitespace.
You could use the replaceAll method to remove all the whitespace from a String:
If you didn't know already, the \\s+ just means one or more whitespace chars
You could use the same method to remove punctuation. Just be mindful, because for example if you do str = str.replaceAll(".", "");, you'll end up with a blank String (a dot means everything but a newline). You would have to do this: str = str.replaceAll("\\.", "");
edit: almost forgot, this is much easier:
The \\W+ means to remove everything that's not a letter (space, punctuation, etc.)
You could use the replaceAll method to remove all the whitespace from a String:
str = str.replaceAll("\\s+", "");
If you didn't know already, the \\s+ just means one or more whitespace chars
You could use the same method to remove punctuation. Just be mindful, because for example if you do str = str.replaceAll(".", "");, you'll end up with a blank String (a dot means everything but a newline). You would have to do this: str = str.replaceAll("\\.", "");
edit: almost forgot, this is much easier:
str = str.replaceAll("\\W+", "");
The \\W+ means to remove everything that's not a letter (space, punctuation, etc.)
This post has been edited by erik.price: 28 March 2010 - 04:53 PM
Page 1 of 1
|
|

New Topic/Question
Reply
MultiQuote








|