How do I remove trailing white space from a string?

The trim method of a String class removes leading and trailing white space from a string. In this example we use a regular expression to remove only the trailing white spaces from a string.

package org.kodejava.example.lang;

public class TrailingSpace {
    public static void main(String[] args) {
	String text = "     tattarrattat     ";

	//
	// Using a regular expression to remove only the trailing white space in
	// a string
	//
	text = text.replaceAll("\s+$", "");
	System.out.println("Text: " + text);
    }
}

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply