Search code examples
javaregexstringtrim

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


Solution

  • 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*