Removing White Space

Reference KnpCode tutorial page

trim

The trim() method returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to ‘U+0020’ (the space character). Note that str.trim() does not change the str object, but returns a new String object.

C:\ece538\white_space>java white1
before:   Hello    World
 after: Hello    World


public class white1 {
    public static void main(String[] args) {    
        String str = "  Hello    World        ";
	System.out.println("before: " + str);
        str = str.trim();
        System.out.println(" after: " + str);
    }
}


strip

The strip() method internally uses Character.isWhitespace() to check for white spaces which provides a much wider definition of whitespaces than trim().

Let’s try to clarify it with an example where a unicode character ‘\u2002’ is used which is not recognized by trim() method.

C:\ece538\white_space>java white2
before: ?   Hello World!   ?
  trim: ?   Hello World!   ?
 strip: Hello World!


public class white2 {
    public static void main(String[] args) {    
        String str = '\u2002' +"   Hello World!   "+ '\u2002';
	System.out.println("before: " + str);
        str = str.trim();
        System.out.println("  trim: " + str);
	str = str.strip();
        System.out.println(" strip: " + str);
    }
}

Removing all white-space

If you have to remove spaces in between the words too apart from leading and trailing spaces then replaceAll() method can be used. replaceAll(String regex, String replacement) replaces each substring of this string that matches the given regular expression with the given replacement. By passing “\\s+” as regex which matches one or many whitespaces and “” as replacement for those whitespaces you can remove all whitespaces from a String.

C:\ece538\white_space>java white3
before:    Hello World!
 after: HelloWorld!


public class white3 {
    public static void main(String[] args) {    
        String str = "   Hello World!   ";
	System.out.println("before: " + str);
        str = str.replaceAll("\\s+", "");
        System.out.println(" after: " + str);
    }
}

Using with split

I like to use trim with split

C:\ece538\HTML>java white4
---no trim
        empty string
        Hello
        World!
---with trim
        Hello
        World!


public class white4 {
    public static void main(String[] args) {    
        String str = "   Hello   World!    ";
        String[] tokens = str.split("\\s+");
        System.out.println("---no trim");
        for (String s: tokens) {
	if (s.equals("")) System.out.println("\tempty string");
	else System.out.println("\t" + s);
       }

        System.out.println("---with trim");
        tokens = str.trim().split("\\s+");
        for (String s: tokens) System.out.println("\t" + s);
    }
}


Maintained by John Loomis, updated Thu Apr 16 17:33:25 2020