How do I remove leading white space from a string?

The trim() method of a String class removes both 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 org.kodejava.example.lang;

public class LeadingSpace {
    public static void main(String[] args) {
        String text = "     tattarrattat     ";
        System.out.println("Original      = " + text);
        System.out.println("text.length() = " + text.length());

        // Using regular expression to remove only the leading white
        // space in string
        text = text.replaceAll("^\\s+", "");
        System.out.println("Result        = " + text);
        System.out.println("text.length() = " + text.length());
Original      =      tattarrattat     
text.length() = 22
Result        = tattarrattat     
text.length() = 17

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.