How to remove Whitespace between String – Java
Today i play around with some funny and simple thing in Java, frankly i really do not know about it. For example, see code snippets :
if(StringUtils.hasLength(sText) { sText= sText.replaceAll(" ", " AND "); }
What i trying to do is remove all whitespace between a string. for example, user key in “Hello Google”, it will replace as “Hello AND Google”, ya this is correct if user only enter one space between words.
"Hello Google" ---> "Hello AND Google"
But how about user key in many spaces in between? For example
"Hello Google" ---> "Hello AND AND AND AND AND Google"
Above is not what i want, should i replace it as below?
if(StringUtils.hasLength(sText) { sText= sText.replaceAll(" ", " AND "); sText= sText.replaceAll(" ", " AND "); sText= sText.replaceAll(" ", " AND "); sText= sText.replaceAll(" ", " AND "); sText= sText.replaceAll(" ", " AND "); }
ya we can replace as many as we like, but this is not so effective and dynamic enough.
Solution
In this case, you should use regular expression to solve it.
if(StringUtils.hasLength(sText) { sText= sText.replaceAll("\\s+", " AND "); }
Great , exactly what i want, Regular Expression ROCK!!!

Here is a nice way of removing white space from String in Java
public class RemoveSpace {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s=”hello hai this is karthik”;
System.out.println( s.replaceAll(“\\s+”, ” “));
}
}
//input:hello hai this is karthik
//output:hello hai this is karthik
Thanks a lot, this code helped me a lot :) ….
but if i want to replace all multiple whitespace character not single then
Yes… Regular expression is really rock.
This is it.
Thank you
Found here the solution.Exactly what I was searching the internet for …
Thanks
I have a combobox value like abc_45;I need only the id such as 45 to store into the database while selected.
please help…..
Although your conclusion regarding the regex pattern is correct, the function you “suggest” as a bad example is actually worse than just bad practice. It simply won’t work.
The first replaceAll used on
"Hello Google"will result in
"Hello AND AND AND AND AND AND AND AND AND AND AND AND Google"and the subsequent replaceAlls will never be matching anything.
ya agreed, the regex solution is the correct solution.
i got it boss… Excellent job keep it up……….
which libray file i have to import for this function…. mail me ..help please
Nice one.. u rock!!
Thanks for take your time to post such a usefull tips, this is what I was looking for.
Thanks again,
Emmanuel
Good to heard this is useful, thanks
Excellent!
Thank you!!
Exactly what I was looking for!
Cheers
Regular Expression IS ROCK ~