is there another way how to remove WhiteSpace Char(s) from String
1) other as I know
myString.trim()
Pattern.compile("\\s");
2) is there another reason(s) search/look for an another/different method as I using
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".
trim() method removes the leading and trailing spaces present in the string. strip method removes the leading and trailing spaces present in the string. Also, it is Uniset/Unicode character aware. stripleading() method removes the spaces present at the beginning of the string.
Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
The replaceAll() method accepts a string and a regular expression replaces the matched characters with the given string. To remove all the white spaces from an input string, invoke the replaceAll() method on it bypassing the above mentioned regular expression and an empty string as inputs.
Guava has a preconfigured CharMatcher
for whitespace()
. It works with unicode as well.
Sample usage:
System.out.println(CharMatcher.whitespace().removeFrom("H \ne\tl\u200al \to "));
Output:
Hello
The CharMatcher also has many other nice features, one of my favorites is the collapseFrom()
method, which replaces multiple occurences with a single character:
System.out.println(
CharMatcher.whitespace().collapseFrom("H \ne\tl\u200al \to ", '*'));
Output:
Hello*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With