java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to remove leading 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 leading white spaces from a string.

package com.javacoderanch.example.lang;

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

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