How do I remove all whitespace from a String?
Author: Deron Eriksson
Description: This Java example shows how to remove all whitespace from a String.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The deleteWhitespace() method of the StringUtils class of the Commons LangS library removes all whitespace characters from a String. This is demonstrated by the RemoveAllWhitespaceTest class:

RemoveAllWhitespaceTest.java

package test;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;

public class RemoveAllWhitespaceTest {

	public static void main(String[] args) throws IOException {

		String str1 = "\n\tThis is my string \n \r\n  !";
		System.out.println("Original String:");
		System.out.println("[" + str1 + "]");
		System.out.println("Whitespace Removed:");
		System.out.println("[" + StringUtils.deleteWhitespace(str1) + "]");

		System.out.println();

		String str2 = " , . ! This is another string \t , .";
		System.out.println("Original String:");
		System.out.println("[" + str2 + "]");
		System.out.println("Whitespace Removed:");
		System.out.println("[" + StringUtils.deleteWhitespace(str2) + "]");

	}

}

The output of RemoveAllWhitespaceTest's execution is shown here:

Results

Original String:
[
	This is my string 
 
  !]
Whitespace Removed:
[Thisismystring!]

Original String:
[ , . ! This is another string 	 , .]
Whitespace Removed:
[,.!Thisisanotherstring,.]