Programming Exercise - II ReplaceAll() method in Java.
Hello All, I got some more time to write another piece of a small algorithm tweaking a little bit. Creating an usecase to use replaceAll method.
Question : I am taking a string as input and I need to find whether it is palindrome or not. It is a simple question as long as we think string doesn’t have any special characters. Ex : “K a,y”ak” should return true as it is a palindrome without any special characters. With our usual approach it won’t.
Solution : Thanks to Java libraries we have a method called replaceAll which replaces all symbols in our string with whichever ‘value’ we provide.
Syntax : String s;
s=s.replaceAll(“Regex”,”value”);
Lets code using above syntax. Here I want to remove all spaces in my string s and check for palindrome.
boolean isPalindrome(String s)
{
s = s.replaceAll(” “,”“); // Taking off spaces. We can write “or”(” “|”.”|”%”) operations in the regex method to replace multiple special symbols in our string.
int n = s.length();
if(n%2 ==0) // Even length
{
for(int i=0;i<n/2- 1 ; i++) // Looping only half
{
if((s.charAt(i) == s.charAt(n-1-i) )
return true;
else
return false;
}
}
else // Odd length
{
for(int i=0; i< n/2 - 1; i++)
{
if(s.charAt(i) == s.charAt(n-1-i) )
{
return true;
}
else
return false;
}
}
}
Suggestions and inputs are most welcome.