Java String trimLeadingWhitespace() Utility Method

This page contains the source code of Java String trimLeadingWhitespace() utility method - Trim leading whitespace from the given String.

Java trimLeadingWhitespace() Utility Method

The following trimLeadingWhitespace() utility method trim leading whitespace from the given String:
package com.javaguides.strings.utils;

public class StringTrimUtil {

     * Trim leading whitespace from the given {@code String}.
     * @param str the {@code String} to check
     * @return the trimmed {@code String}
     * @see java.lang.Character#isWhitespace
    public static String trimLeadingWhitespace(String str) {
        if (!hasLength(str)) {
            return str;

        StringBuilder sb = new StringBuilder(str);
        while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
        return sb.toString();

    public static boolean hasLength(String str) {
        return (str != null && str.length() > 0);

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course