Changwang Zhang
Changwang Zhang

Reputation: 2483

how to only trim the blanks in the beginning of a string

Java method: String.trim() trim blanks (white space, new line, etc.) at both the beginning and end of a string.

How to only trim the blanks in the beginning of a String?

Upvotes: 1

Views: 1933

Answers (4)

A-SM
A-SM

Reputation: 884

Remove the leading blank spaces:

str = str.replaceFirst("\\s+","");

Upvotes: 0

53by97
53by97

Reputation: 425

If you want to give your own implementation, then you can use such a method-

package com.kvvssut.misc;

public class TrimAtFirst {

    public static void main(String[] args) {
        System.out.println(trimAtFirst("      \n   \r   \t  You need to trim only before spaces!    "));
    }

    private static String trimAtFirst(String string) {

        int start = 0;
        int len = string.length();

        for (; start < len; start++) {
            char ch = string.charAt(start);
            if (ch != ' ') {
                if (!(ch == '\n' || ch == '\t' || ch == '\r')) {    // include others- I am not sure if more. Also, you can customize based on your needs!
                    break;
                }
            }
        }

        return string.substring(start, len);
    }

}

output- "You need to trim only before spaces! "

Upvotes: 0

AntonH
AntonH

Reputation: 6437

You can with this:

myString = myString.replaceAll("^\\s+", "")

If you want to remove only specific whitespaces (such as, only blanks), you would replace \\s with either the specific character (eg: "^ +" for only blanks) or the character class (eg: "^[ \\t]+" for blanks and tabs).

Edit As per @Pshemo's remark, you can use replaceFirst instead of replaceAll.

Upvotes: 2

Sajad Karuthedath
Sajad Karuthedath

Reputation: 15767

try this too

to trim beginning

myString.replaceAll("^\\s+", "");

and to trim trailing

myString.replaceAll("\\s+$", "");

Upvotes: 1

Related Questions