Java Code to Check if String having Spaces is a Palindrome
In one of our previous articles, we have written code to verify if a String is a Palindrome. We utilized the magic of For loops to Reverse a String and verify if its Palindrome.
Now, if the Interviewer decides to make the question a bit more difficult, the next step can be to verify that the Input String is having some Spaces, or special characters is a Palindrome or not, and still your code should be able to handle that. (Another Important Java Interview Question!)
Its sounds difficult, but if you carefully look at the question, there is a simple trick to solve it. If we remove the extra characters and then compare the input string, we would be able to identify if the string is a Palindrome.
So let's get started!
This is our base code to if a String is a Palindrome. Reversing the String is achieved in another function Reverse a String.
/** * Check if String is palindrome * * @author computengine.com * @param input * @return */ public boolean checkPalindrome(String input) { ReverseString rs = new ReverseString(); // if a string is equal to its reverse, its a palindrome if (input.equalsIgnoreCase(rs.reverseString(input))) return true; else return false; }
Without making any changes to the original logic, we are simply going to add one little extra logic to the code, which will solve our problem. What is that? String replace function.
input = input.replace(" ", "");
Is that it? Yes! You can modify the function to cover any special characters you want to remove from the verification.
So, the final function that will do the job for us, will look something like this.
/** * Check if String having spaces in between is still a palindrome * * @author computengine.com * @param input * @return * */ public boolean checkPalindromeWithSpaces(String input) { ReverseString rs = new ReverseString(); input = input.replace(" ", ""); if (input.equalsIgnoreCase(rs.reverseString(input))) return true; else return false; }
Let's check the output as well. Let's call the function to check that.
System.out.println("Input String is Palindrome: " + cp.checkPalindromeWithSpaces("I am mai"));
Input String: Iammai
Reversed String: iammaI
Input String is Palindrome: true
Thanks for Reading the Article. If you have reached this far, we hope that the article was useful to you! Please Like/Share/Follow us on Facebook, Twitter, Tumblr.
Comments
Post a Comment