Monday, March 5, 2012

How do I remove trailing white space from a string in Java?


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.
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);
    }
}

No comments:

Post a Comment