How do I remove whitespace from the front and back of a String?
Author: Deron Eriksson
Description: This Java example shows how to remove whitespace or other characters from the start and end of a String.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)

The strip(String str) method of the StringUtils class of the Commons LangS library can be used to remove all whitespace characters from the beginning and end of a String. In addition, the StringUtils class has a strip(String str, String stripChars) method that lets you specify different characters to strip from the front and back of the String. The StripTest class demonstrates both of these methods.

package test;


import org.apache.commons.lang.StringUtils;

public class StripTest {

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

		String str1 = "\n\tThis is my string   ";
		System.out.println("Original String:");
		System.out.println("[" + str1 + "]");
		System.out.println("Stripped String via StringUtils.strip(str1):");
		System.out.println("[" + StringUtils.strip(str1) + "]");


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



The console output of StripTest is shown below.


Original String:
	This is my string   ]
Stripped String via StringUtils.strip(str1):
[This is my string]

Original String:
[ , . ! This is another string 	 , .]
Stripped String via StringUtils.strip(str2, " \t,."):
[! This is another string]