Java String trimTrailingWhitespace() Utility Method - Trim Trailing Whitespace from a String

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

Java trimTrailingWhitespace() Utility Method

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

public class StringTrimUtil {

    /**
     * Trim trailing 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 trimTrailingWhitespace(String str) {
        if (!hasLength(str)) {
            return str;
        }

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

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

Related Utility Methods


Comments