How to Remove Leading and Trailing White Space From a String in Java

In this short article, we will write a Java program to remove or trim leading and trailing whitespace from the given String in Java.

Java Program to Remove Leading and Trailing White Space From a String

We are using built-in Character.isWhitespace() method to check if the first and last character is white space. Here is a complete Java program:
package com.javaguides.corejava.string;

/**
 * @author Ramesh Fadatare
 *
 */
public class StringTrimLeadingAndTrailingWhitespace {

    public static void main(String[] args) {
        String str = "  Java Guides ";
        String result = trimWhitespace(str);
        System.out.println(result);
    }
    /**
     * Trim leading and 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 trimWhitespace(String str) {
        if (!(str != null && !str.isEmpty())) {
            return str;
        }

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

Related String Programs

Comments