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 Stringchar
, 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.trim() , from Java 11, removes characters for whichstrip() is true. That includes most Unicode spaces, such as the em space, but deliberately excludes the no-break spaces.Character.isWhitespace- The regex class
matches only six ASCII characters: space, tab, line feed, vertical tab, form feed and carriage return. With the\s flag it follows Unicode instead, and then it also matches no-break spaces.(?U)
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.
| Method | Since | Removes | Best for |
|---|---|---|---|
strip()stripLeading()stripTrailing() | Java 11 | Unicode whitespace at the ends | Trimming user input |
trim() | Java 1.0 | Characters up to U+0020 at the ends | Old code; ASCII-only data |
replace(" ", "") | Java 5 | The space character only, everywhere | Removing spaces but keeping tabs and line breaks |
replaceAll("\\s", "") | Java 1.4 | ASCII whitespace everywhere | Deleting all whitespace |
replaceAll("\\s+", " ") | Java 1.4 | Runs of whitespace, replaced by one space | Normalizing text to single spaces |
lines()stripIndent() | Java 11, Java 15 | Per-line whitespace and common indentation | Multi-line text |
Loop with Character.isWhitespace | Java 1.1 | Whatever your test says | Hot 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\n
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:
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]
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.strip() kept the trailingstripLeading() and\n kept the leading spaces, which is what you want when indentation or a line ending must survive.stripTrailing() deleted all space characters, yet the result still containsreplace(" ", "") and\t . This surprises people who expect "spaces" to mean whitespace in general.\n removed every whitespace character and producedreplaceAll("\\s", "") . In Java source the backslash must be doubled, so the regexHello,bigworld is written\s ."\\s" turned each run into a single space and then trimmed the ends, givingreplaceAll("\\s+", " ").strip() . This is the usual way to clean a name or a search query typed by a user.Hello, big world
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.
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:
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
treats as whitespace.Character.isWhitespace andtrim both remove it, butstrip does not.\s - The no-break space U+00A0, the figure space U+2007 and the narrow no-break space U+202F are the most common trap.
says yes, butisSpaceChar says no on purpose, because they exist to stop a line from breaking. SoisWhitespace keeps them, and so does plainstrip() .\s - The em space and the ideographic space U+3000, used in Chinese and Japanese text, are removed by
but not bystrip() ortrim() .\s , which turns on(?U)\s , matches every space in the table.Pattern.UNICODE_CHARACTER_CLASS , the horizontal whitespace class added in Java 8, also matches all the spaces and the tab, but not line breaks.\h- 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 equalsTotal: 42 EUR
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:
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
andtrim() both removed only the trailing space andstrip() , going from 19 to 16 characters. Both stopped at the no-break spaces at the start.\r\n- Plain
did no better.\s+ handled every space and got down to 14 characters, but the zero width space is still there between the colon and 42.(?U)\s+ - The cleaner first deletes the zero width characters (U+200B to U+200D and U+FEFF), then replaces runs of any Unicode space separator (
) or ASCII whitespace with one space. The result has 13 characters and equals the expected string.\p{Z}
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
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.
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 |
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
, added in Java 11, splits onlines() ,\n and\r and returns a lazy stream. The text has 5 lines; the final newline does not create a sixth.\r\n- Stripping each line and filtering out blank ones gives the three lines of content.
alone keeps the indentation but removes the trailing spaces and the tab.stripTrailing , 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 finalstripIndent() , with zero indentation.\n- Without the final newline, the smallest indentation is 4, so
loses all its spaces andfirst line keeps 4 of its 8.indented more - To collapse everything to one line,
treats line breaks like any other whitespace.replaceAll("\\s+", " ")
Common mistakes
Each of these mistakes compiles without a warning and produces a wrong result quietly, so the program runs all five.
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:
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
- Calling
on its own line throws the result away, soname.strip(); still has its spaces. The value must be assigned.name - Since Java 15,
with a single backslash is a valid string escape meaning one space (JEP 378).\s therefore compiles, but its regex is a plain space: it kept the tab and returned 4 characters instead of 3.replaceAll("\s", "") on text with leading and doubled spaces produces empty strings. Evensplit(" ") returns an empty first element when the text starts with whitespace, so strip first. More insplit("\\s+")splitting strings . can only substitute one character for another; there is no emptyreplace(char, char) . To delete, use thechar version,CharSequence .replace(" ", "")- All these methods are instance methods, so they throw
on a null reference. A small helper, or a library method such as Apache CommonsNullPointerException , handles null explicitly.StringUtils.isBlank
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.
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):
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
loop and theStringBuilder stream were about two to three times faster than the regex versions. A regex engine does more work per character than onechars() call.isWhitespace - Precompiling the pattern hardly matters for one long string, because the pattern is compiled once either way.
- For many short strings it does matter.
compiles its regex on every call, so the precompiledString.replaceAll was noticeably faster, and the loop was faster still, four to five times quicker thanPattern .String.replaceAll - The loop sizes its
to the input length up front, so it never has to grow its buffer.StringBuilder
In ordinary code, prefer the readable one-liners. Keep a precompiled Patternstatic final
Which method to use
| Goal | Code |
|---|---|
| Trim both ends of user input | s.strip() |
| Trim one end only | s.stripLeading()s.stripTrailing() |
| Remove every whitespace character | s.replaceAll("\\s", "") |
| Collapse runs to one space | s.replaceAll("\\s+", " ").strip() |
| Also handle no-break and other Unicode spaces | s.replaceAll("[\\p{Z}\\s]+", " ").strip() |
| Remove spaces but keep tabs and line breaks | s.replace(" ", "") |
| Clean each line of multi-line text | s.lines().map(String::strip) |
| Remove common indentation | s.stripIndent() |
| Check for nothing but whitespace | s.isBlank() |
| Tight loop over millions of strings | A StringBuilderPattern |
For replacing other text, see