Remove Whitespace from a String

"Remove spaces" can mean trimming the ends, deleting every whitespace character, or squeezing runs of whitespace down to one space. Java has a different method for each, and they disagree about which characters count as whitespace. This page shows what each method removes, how to clean text pasted from the web, the common traps, and which approach is fastest.

Contents

What counts as whitespace in Java

A String is a sequence of UTF-16 char values, and "whitespace" is not one fixed set of them. Each method that removes spaces has its own definition, written at a different time in Java's history:

  • trim(), from Java 1.0, removes every character with a code of U+0020 or less from both ends. That covers the space, tab and line breaks, but also control characters such as U+0000, and no Unicode space at all.
  • strip(), from Java 11, removes characters for which Character.isWhitespace is true. That includes most Unicode spaces, such as the em space, but deliberately excludes the no-break spaces.
  • The regex class \s matches only six ASCII characters: space, tab, line feed, vertical tab, form feed and carriage return. With the (?U) flag it follows Unicode instead, and then it also matches no-break spaces.

Strings are immutable, so none of these methods changes the original. Each returns a new string, or the same object when there was nothing to remove.

Methods for removing whitespace
MethodSinceRemovesBest for
strip(), stripLeading(), stripTrailing()Java 11Unicode whitespace at the endsTrimming user input
trim()Java 1.0Characters up to U+0020 at the endsOld code; ASCII-only data
replace(" ", "")Java 5The space character only, everywhereRemoving spaces but keeping tabs and line breaks
replaceAll("\\s", "")Java 1.4ASCII whitespace everywhereDeleting all whitespace
replaceAll("\\s+", " ")Java 1.4Runs of whitespace, replaced by one spaceNormalizing text to single spaces
lines(), stripIndent()Java 11, Java 15Per-line whitespace and common indentationMulti-line text
Loop with Character.isWhitespaceJava 1.1Whatever your test saysHot code paths and custom rules

The programs below are complete classes, compiled and run on JDK 21. Each can be saved to a file and run with java ClassName.java.

Ends, everything, or runs: the basic methods

The input has two leading spaces, a tab, a run of three spaces in the middle, and a trailing space followed by a newline, so every method has something different to do. Brackets in the output show where each result starts and ends, and tabs and newlines are printed as \t and \n.

Java
public class RemoveSpaces {

    public static void main(String[] args) {
        String input = "  Hello,\t big   world \n";

        show("original", input);
        show("strip()", input.strip());                         // ends only
        show("stripLeading()", input.stripLeading());
        show("stripTrailing()", input.stripTrailing());
        show("replace(\" \", \"\")", input.replace(" ", ""));    // spaces only
        show("replaceAll(\"\\\\s\", \"\")", input.replaceAll("\\s", ""));  // all whitespace
        String collapsed = input.replaceAll("\\s+", " ").strip();
        show("replaceAll(\"\\\\s+\", \" \").strip()", collapsed);
    }

    // Brackets make leading and trailing whitespace visible; \t and \n are shown as text
    static void show(String label, String s) {
        String visible = s.replace("\t", "\\t").replace("\n", "\\n");
        System.out.printf("%-34s [%s]%n", label, visible);
    }
}

Output:

Output
original                           [  Hello,\t big   world \n]
strip()                            [Hello,\t big   world]
stripLeading()                     [Hello,\t big   world \n]
stripTrailing()                    [  Hello,\t big   world]
replace(" ", "")                   [Hello,\tbigworld\n]
replaceAll("\\s", "")              [Hello,bigworld]
replaceAll("\\s+", " ").strip()    [Hello, big world]
  • strip() removed the two leading spaces and the trailing space and newline, but the tab and the three inner spaces are untouched. It only ever looks at the ends.
  • stripLeading() kept the trailing \n and stripTrailing() kept the leading spaces, which is what you want when indentation or a line ending must survive.
  • replace(" ", "") deleted all space characters, yet the result still contains \t and \n. This surprises people who expect "spaces" to mean whitespace in general.
  • replaceAll("\\s", "") removed every whitespace character and produced Hello,bigworld. In Java source the backslash must be doubled, so the regex \s is written "\\s".
  • replaceAll("\\s+", " ").strip() turned each run into a single space and then trimmed the ends, giving Hello, big world. This is the usual way to clean a name or a search query typed by a user.

Which characters each method removes

The table that the next program prints is the quickest way to see why methods disagree. It tests twelve characters: the ASCII ones, the control character U+001C, and the Unicode spaces most often found in pasted text, including two invisible characters that are not spaces at all.

Java
import java.util.regex.Pattern;

public class WhitespaceKinds {

    public static void main(String[] args) {
        char[] chars = {' ', '\t', '\n', '\u000B', '\u001C', '\u00A0', '\u2003',
            '\u2007', '\u202F', '\u3000', '\u200B', '\uFEFF'};
        String[] names = {"SPACE", "TAB", "LINE FEED", "VERTICAL TAB", "FILE SEPARATOR",
            "NO-BREAK SPACE", "EM SPACE", "FIGURE SPACE", "NARROW NO-BREAK", "IDEOGRAPHIC SPACE",
            "ZERO WIDTH SPACE", "BOM (ZWNBSP)"};
        Pattern ascii = Pattern.compile("\\s");
        Pattern unicode = Pattern.compile("(?U)\\s");
        Pattern horizontal = Pattern.compile("\\h");

        System.out.printf("%-6s %-18s %5s %5s %6s %6s %4s %6s %3s%n", "code", "name",
            "trim", "strip", "isWS", "isSpace", "\\s", "(?U)\\s", "\\h");
        for (int i = 0; i < chars.length; i++) {
            String c = String.valueOf(chars[i]);
            String row = "U+%04X %-18s %5s %5s %6s %7s %4s %6s %3s%n";
            System.out.printf(row, (int) chars[i], names[i],
                yes(c.trim().isEmpty()), yes(c.strip().isEmpty()),
                yes(Character.isWhitespace(chars[i])), yes(Character.isSpaceChar(chars[i])),
                yes(ascii.matcher(c).matches()), yes(unicode.matcher(c).matches()),
                yes(horizontal.matcher(c).matches()));
        }
    }

    static String yes(boolean b) {
        return b ? "yes" : "-";
    }
}

Output:

Output
code   name                trim strip   isWS isSpace   \s (?U)\s  \h
U+0020 SPACE                yes   yes    yes     yes  yes    yes yes
U+0009 TAB                  yes   yes    yes       -  yes    yes yes
U+000A LINE FEED            yes   yes    yes       -  yes    yes   -
U+000B VERTICAL TAB         yes   yes    yes       -  yes    yes   -
U+001C FILE SEPARATOR       yes   yes    yes       -    -      -   -
U+00A0 NO-BREAK SPACE         -     -      -     yes    -    yes yes
U+2003 EM SPACE               -   yes    yes     yes    -    yes yes
U+2007 FIGURE SPACE           -     -      -     yes    -    yes yes
U+202F NARROW NO-BREAK        -     -      -     yes    -    yes yes
U+3000 IDEOGRAPHIC SPACE      -   yes    yes     yes    -    yes yes
U+200B ZERO WIDTH SPACE       -     -      -       -    -      -   -
U+FEFF BOM (ZWNBSP)           -     -      -       -    -      -   -
  • The first four rows are whitespace by every definition, so for plain ASCII text all methods agree.
  • U+001C, the file separator, is a control character that Character.isWhitespace treats as whitespace. trim and strip both remove it, but \s does not.
  • The no-break space U+00A0, the figure space U+2007 and the narrow no-break space U+202F are the most common trap. isSpaceChar says yes, but isWhitespace says no on purpose, because they exist to stop a line from breaking. So strip() keeps them, and so does plain \s.
  • The em space and the ideographic space U+3000, used in Chinese and Japanese text, are removed by strip() but not by trim() or \s.
  • (?U)\s, which turns on Pattern.UNICODE_CHARACTER_CLASS, matches every space in the table. \h, the horizontal whitespace class added in Java 8, also matches all the spaces and the tab, but not line breaks.
  • The zero width space U+200B and U+FEFF, the byte order mark, are invisible but are not whitespace under any definition. No method removes them, so they must be named explicitly.

Cleaning text pasted from the web

Values copied from a web page, a PDF or a spreadsheet often look right but fail equals. This input reads Total: 42 EUR on screen, but contains two leading no-break spaces, a zero width space, an em space and a Windows line ending.

Java
public class CleanPasted {

    public static void main(String[] args) {
        // What a cell copied from a web page or a spreadsheet often looks like
        String pasted = "\u00A0\u00A0Total:\u00A0\u200B42\u2003EUR \r\n";
        String expected = "Total: 42 EUR";

        show("pasted", pasted);
        show("trim()", pasted.trim());
        show("strip()", pasted.strip());
        show("replaceAll(\\s+)", pasted.replaceAll("\\s+", " ").strip());
        show("replaceAll((?U)\\s+)", pasted.replaceAll("(?U)\\s+", " ").strip());

        String clean = pasted
            .replaceAll("[\\u200B\\u200C\\u200D\\uFEFF]", "")   // invisible, zero width
            .replaceAll("[\\p{Z}\\s]+", " ")                    // every kind of space
            .strip();
        show("cleaned", clean);
        System.out.println("equals expected? " + clean.equals(expected));
    }

    // Prints non-ASCII characters and control characters as \\uXXXX so they can be seen
    static void show(String label, String s) {
        StringBuilder sb = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (c < 32 || c > 126) {
                sb.append(String.format("\\u%04X", (int) c));
            } else {
                sb.append(c);
            }
        }
        System.out.printf("%-22s len %2d [%s]%n", label, s.length(), sb);
    }
}

Output:

Output
pasted                 len 19 [\u00A0\u00A0Total:\u00A0\u200B42\u2003EUR \u000D\u000A]
trim()                 len 16 [\u00A0\u00A0Total:\u00A0\u200B42\u2003EUR]
strip()                len 16 [\u00A0\u00A0Total:\u00A0\u200B42\u2003EUR]
replaceAll(\s+)        len 16 [\u00A0\u00A0Total:\u00A0\u200B42\u2003EUR]
replaceAll((?U)\s+)    len 14 [Total: \u200B42 EUR]
cleaned                len 13 [Total: 42 EUR]
equals expected? true
  • trim() and strip() both removed only the trailing space and \r\n, going from 19 to 16 characters. Both stopped at the no-break spaces at the start.
  • Plain \s+ did no better. (?U)\s+ handled every space and got down to 14 characters, but the zero width space is still there between the colon and 42.
  • The cleaner first deletes the zero width characters (U+200B to U+200D and U+FEFF), then replaces runs of any Unicode space separator (\p{Z}) or ASCII whitespace with one space. The result has 13 characters and equals the expected string.

Use this kind of cleaning at the edge of a system, where text enters it, and store the clean value. For checking what a string really contains, printing each code point as this program does is more reliable than looking at it; see characters and code points.

Multi-line text: lines, stripTrailing and stripIndent

For text with several lines, such as a configuration value or a message template, whitespace usually has to be handled per line. The test text has indentation, trailing spaces and a tab, a blank line that holds only spaces, and an empty line.

Java
import java.util.stream.Collectors;

public class MultiLine {

    public static void main(String[] args) {
        String text = "    first line   \n"
            + "\n"
            + "        indented more\t\n"
            + "   \n"
            + "    last line\n";

        System.out.println("lines in text:      " + text.lines().count());

        String noBlank = text.lines()
            .map(String::strip)
            .filter(line -> !line.isBlank())
            .collect(Collectors.joining("|"));
        System.out.println("stripped, no blank: " + noBlank);

        String noTrailing = text.lines()
            .map(String::stripTrailing)
            .collect(Collectors.joining("|"));
        System.out.println("stripTrailing only: " + noTrailing);

        // stripIndent removes the indentation common to all non-blank lines,
        // but the empty last line after the final \n counts too
        System.out.println("stripIndent, ends with \\n: " + visible(text.stripIndent()));
        String noFinalNewline = text.substring(0, text.length() - 1);
        System.out.println("stripIndent, no final \\n: " + visible(noFinalNewline.stripIndent()));

        String oneLine = text.replaceAll("\\s+", " ").strip();
        System.out.println("one line:           " + oneLine);
    }

    static String visible(String s) {
        return "[" + s.replace("\n", "|") + "]";
    }
}

Output (line breaks are shown as |):

Output
lines in text:      5
stripped, no blank: first line|indented more|last line
stripTrailing only:     first line||        indented more||    last line
stripIndent, ends with \n: [    first line||        indented more||    last line|]
stripIndent, no final \n: [first line||    indented more||last line]
one line:           first line indented more last line
  • lines(), added in Java 11, splits on \n, \r and \r\n and returns a lazy stream. The text has 5 lines; the final newline does not create a sixth.
  • Stripping each line and filtering out blank ones gives the three lines of content. stripTrailing alone keeps the indentation but removes the trailing spaces and the tab.
  • stripIndent(), added in Java 15 for text blocks, removes the indentation that all non-blank lines share and strips trailing whitespace from each line. The trap is in the first result: nothing was dedented. Its documentation says the last line counts even when blank, and here the last line is the empty string after the final \n, with zero indentation.
  • Without the final newline, the smallest indentation is 4, so first line loses all its spaces and indented more keeps 4 of its 8.
  • To collapse everything to one line, replaceAll("\\s+", " ") treats line breaks like any other whitespace.

Common mistakes

Each of these mistakes compiles without a warning and produces a wrong result quietly, so the program runs all five.

Java
import java.util.Arrays;

public class Pitfalls {

    public static void main(String[] args) {
        // 1. Strings are immutable: the result must be used
        String name = "  Ada  ";
        name.strip();
        System.out.println("1. after name.strip();      [" + name + "]");
        name = name.strip();
        System.out.println("   after name = name.strip(); [" + name + "]");

        // 2. "\s" (one backslash) is a string escape for a single space since Java 15
        String text = "a\tb c";
        int regex = text.replaceAll("\\s", "").length();
        int space = text.replaceAll("\s", "").length();
        System.out.println("2. replaceAll(\"\\\\s\", \"\") -> " + regex + " chars");
        System.out.println("   replaceAll(\"\\s\", \"\")  -> " + space + " chars");

        // 3. split on leading whitespace gives an empty first element
        String words = "  red  green blue";
        System.out.println("3. split(\" \")        " + Arrays.toString(words.split(" ")));
        System.out.println("   split(\"\\\\s+\")     " + Arrays.toString(words.split("\\s+")));
        System.out.println("   strip().split(\"\\\\s+\") "
            + Arrays.toString(words.strip().split("\\s+")));

        // 4. replace(char, char) cannot delete: there is no empty char
        System.out.println("4. replace(' ', '_')  " + "a b c".replace(' ', '_')
            + ", replace(\" \", \"\") " + "a b c".replace(" ", ""));

        // 5. isBlank and strip throw on null
        String missing = null;
        try {
            System.out.println(missing.isBlank());
        } catch (NullPointerException e) {
            System.out.println("5. null.isBlank() -> NullPointerException");
        }
        System.out.println("   isNullOrBlank(null) -> " + isNullOrBlank(missing)
            + ", isNullOrBlank(\" \\t\") -> " + isNullOrBlank(" \t"));
    }

    static boolean isNullOrBlank(String s) {
        return s == null || s.isBlank();
    }
}

Output:

Output
1. after name.strip();      [  Ada  ]
   after name = name.strip(); [Ada]
2. replaceAll("\\s", "") -> 3 chars
   replaceAll("\s", "")  -> 4 chars
3. split(" ")        [, , red, , green, blue]
   split("\\s+")     [, red, green, blue]
   strip().split("\\s+") [red, green, blue]
4. replace(' ', '_')  a_b_c, replace(" ", "") abc
5. null.isBlank() -> NullPointerException
   isNullOrBlank(null) -> true, isNullOrBlank(" \t") -> true
  1. Calling name.strip(); on its own line throws the result away, so name still has its spaces. The value must be assigned.
  2. Since Java 15, \s with a single backslash is a valid string escape meaning one space (JEP 378). replaceAll("\s", "") therefore compiles, but its regex is a plain space: it kept the tab and returned 4 characters instead of 3.
  3. split(" ") on text with leading and doubled spaces produces empty strings. Even split("\\s+") returns an empty first element when the text starts with whitespace, so strip first. More in splitting strings.
  4. replace(char, char) can only substitute one character for another; there is no empty char. To delete, use the CharSequence version, replace(" ", "").
  5. All these methods are instance methods, so they throw NullPointerException on a null reference. A small helper, or a library method such as Apache Commons StringUtils.isBlank, handles null explicitly.

How fast is each approach?

Removing whitespace is usually too cheap to matter, but it can show up when cleaning millions of records. The program removes all whitespace from a 2 million character string with five approaches, then runs three of them on 200,000 short strings. Each timing is the best of 3 runs, and every approach is checked to give the same result.

Java
import java.util.Random;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;

public class RemoveSpeed {

    static final Pattern WS = Pattern.compile("\\s+");

    public static void main(String[] args) {
        Random random = new Random(42);
        StringBuilder sb = new StringBuilder();
        String[] gaps = {" ", "  ", "\t", "\n", " \t "};
        while (sb.length() < 2_000_000) {
            sb.append("word").append(random.nextInt(1000));
            sb.append(gaps[random.nextInt(gaps.length)]);
        }
        String input = sb.toString();
        String reference = input.replaceAll("\\s", "");
        System.out.printf("input %,d chars, result %,d chars%n",
            input.length(), reference.length());

        time("replaceAll(\"\\\\s\", \"\")", input, reference, s -> s.replaceAll("\\s", ""));
        time("replaceAll(\"\\\\s+\", \"\")", input, reference, s -> s.replaceAll("\\s+", ""));
        time("precompiled Pattern", input, reference, s -> WS.matcher(s).replaceAll(""));
        time("StringBuilder loop", input, reference, RemoveSpeed::loop);
        time("chars().filter()", input, reference, s -> s.chars()
            .filter(c -> !Character.isWhitespace(c))
            .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
            .toString());

        // Many short strings: now compiling the regex on every call is the main cost
        String[] shortOnes = new String[200_000];
        for (int i = 0; i < shortOnes.length; i++) {
            shortOnes[i] = " id " + i + "\t";
        }
        System.out.printf("%n%,d short strings%n", shortOnes.length);
        timeMany("String.replaceAll", shortOnes, s -> s.replaceAll("\\s+", ""));
        timeMany("precompiled Pattern", shortOnes, s -> WS.matcher(s).replaceAll(""));
        timeMany("StringBuilder loop", shortOnes, RemoveSpeed::loop);
    }

    static void timeMany(String name, String[] inputs, UnaryOperator<String> f) {
        long best = Long.MAX_VALUE;
        long chars = 0;
        for (int run = 0; run < 3; run++) {
            chars = 0;
            long t0 = System.nanoTime();
            for (String s : inputs) {
                chars += f.apply(s).length();
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("%-24s %6.1f ms  %,d chars kept%n", name, best / 1e6, chars);
    }

    static String loop(String s) {
        StringBuilder out = new StringBuilder(s.length());
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!Character.isWhitespace(c)) {
                out.append(c);
            }
        }
        return out.toString();
    }

    // Best of 3 runs, so JIT compilation in the first run does not decide the result
    static void time(String name, String input, String reference, UnaryOperator<String> f) {
        long best = Long.MAX_VALUE;
        String result = null;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            result = f.apply(input);
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("%-24s %6.1f ms  same result: %b%n", name, best / 1e6,
            result.equals(reference));
    }
}

Output (rough comparison on a 2-CPU Linux machine, JDK 21; times differ between runs and machines):

Output
input 2,000,001 chars, result 1,622,955 chars
replaceAll("\\s", "")      14.0 ms  same result: true
replaceAll("\\s+", "")     14.9 ms  same result: true
precompiled Pattern        14.6 ms  same result: true
StringBuilder loop          5.6 ms  same result: true
chars().filter()            6.3 ms  same result: true

200,000 short strings
String.replaceAll          38.7 ms  1,488,890 chars kept
precompiled Pattern        26.5 ms  1,488,890 chars kept
StringBuilder loop          7.8 ms  1,488,890 chars kept
  • On the long string, the hand-written StringBuilder loop and the chars() stream were about two to three times faster than the regex versions. A regex engine does more work per character than one isWhitespace call.
  • Precompiling the pattern hardly matters for one long string, because the pattern is compiled once either way.
  • For many short strings it does matter. String.replaceAll compiles its regex on every call, so the precompiled Pattern was noticeably faster, and the loop was faster still, four to five times quicker than String.replaceAll.
  • The loop sizes its StringBuilder to the input length up front, so it never has to grow its buffer.

In ordinary code, prefer the readable one-liners. Keep a precompiled Pattern in a static final field when the same regex runs in a loop, as explained on the regular expressions page.

Which method to use

Choosing a way to remove whitespace
GoalCode
Trim both ends of user inputs.strip()
Trim one end onlys.stripLeading() or s.stripTrailing()
Remove every whitespace characters.replaceAll("\\s", "")
Collapse runs to one spaces.replaceAll("\\s+", " ").strip()
Also handle no-break and other Unicode spacess.replaceAll("[\\p{Z}\\s]+", " ").strip()
Remove spaces but keep tabs and line breakss.replace(" ", "")
Clean each line of multi-line texts.lines().map(String::strip)
Remove common indentations.stripIndent(), watching the final newline
Check for nothing but whitespaces.isBlank() (Java 11), after a null check
Tight loop over millions of stringsA StringBuilder loop or a precompiled Pattern

For replacing other text, see replacing text in a string, and for more string helpers, string utility methods.