How to Remove or Trim All White Spaces from a String in Java

In this short article, we look at how to remove or trim all white spaces from a given string in Java.
Let's first we'll write a Java method to trim all whitespace from the given String that is trim white spaces from leading, trailing, and in between characters.

trimAllWhitespace(String str) Method

Let's write a Java method with logic to remove all white spaces.

Logical steps

  1. Iterate over each character of a given String.
  2. Check each character with white space using the built-in Character.isWhitespace(c) method.
  3. If the character is not a white space then append a character to the StringBuilder instance.
  4. Finally, return String via calling the toString() method on the StringBuilder instance.
/**
 * Trim <i>all</i> whitespace from the given {@code String}:
 * leading, trailing, and in between characters.
 * @param str the {@code String} to check
 * @return the trimmed {@code String}
 * @see java.lang.Character#isWhitespace
 */
public static String trimAllWhitespace(String str) {
    if (!hasLength(str)) {
        return str;
    }

    int len = str.length();
    StringBuilder sb = new StringBuilder(str.length());
    for (int i = 0; i < len; i++) {
        char c = str.charAt(i);
        if (!Character.isWhitespace(c)) {
            sb.append(c);
        }
    }
    return sb.toString();
}

Complete Java Program

Here is a complete Java program to demonstrate the above method with the input value " Java Guides ".
package com.javaguides.corejava.string;

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


    public static void main(String[] args) {
        String str = "  Java    Guides    ";
        String result = trimAllWhitespace(str);
        System.out.println(result);
    }
    /**
     * Trim <i>all</i> whitespace from the given {@code String}:
     * leading, trailing, and in between characters.
     * @param str the {@code String} to check
     * @return the trimmed {@code String}
     * @see java.lang.Character#isWhitespace
     */
    public static String trimAllWhitespace(String str) {
        if (!hasLength(str)) {
            return str;
        }

        int len = str.length();
        StringBuilder sb = new StringBuilder(str.length());
        for (int i = 0; i < len; i++) {
            char c = str.charAt(i);
            if (!Character.isWhitespace(c)) {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static boolean hasLength(String str) {
        return (str != null && !str.isEmpty());
    }
}
Output:
JavaGuides

Related Java String Programs with Output

Comments