Remove whitespace from string

This example will show how to remove all whitespace from a string using java, guava and apache commons. In the snippets below we will use various user groups names throughout the midwest.

Straight up Java


This snippet show how to replace all whitespaces using core java jdk String.replaceAll.

public void remove_all_whitespace_java () {

    String dsmJs = "Des Moines JavaScript User Group";

    String removeAllSpaces = dsmJs.replaceAll(" ", "");

    assertEquals("DesMoinesJavaScriptUserGroup", removeAllSpaces);


This snippet will remove all whitespace from a string using a regex expression.

public void remove_all_whitespace_regex() {

    String dsmAUG = "Des Moines, IA Atlassian User Group";

    String removeAllSpaces = dsmAUG.replaceAll("\s", "");

    assertEquals("DesMoines,IAAtlassianUserGroup", removeAllSpaces);

Google Guava

This snippet will remove blank characters from a string using guava Charmatcher. Calling Charmatcher removeFrom method will remove all non matching chars or spaces.

public void remove_all_whitespace_guava () {

    String cijug = "Central Iowa Java Users Group";
    String removeAllSpaces =' ').removeFrom(cijug);

    assertEquals("CentralIowaJavaUsersGroup", removeAllSpaces);

Apache Commons

This snippet will show how to remove empty characters in a string using StringUtils.deleteWhitespace.

public void remove_all_whitespace_apache_commons () {

    String madJug = "Madison Java User Group";

    String removeAllSpaces = StringUtils.deleteWhitespace(madJug);

    assertEquals("MadisonJavaUserGroup", removeAllSpaces);