Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove WhiteSpace Chars from String instance

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

like image 297
mKorbel Avatar asked Aug 30 '11 07:08

mKorbel


People also ask

How do I remove a whitespace character from a string?

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 "".

How can remove space from string in Java?

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.

How do I remove whitespace characters from a string in Python?

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.

How do I get rid of white space in regex?

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.


1 Answers

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*

like image 61
Sean Patrick Floyd Avatar answered Nov 03 '22 11:11

Sean Patrick Floyd