bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java How To's
Java•Java How To's

Java How To - Remove Whitespace from a String

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java How To - Remove Whitespace from a String?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ text = " Java ";
3Order

Put the learning moves in the order that makes the concept easiest to apply.

Remove All Whitespace
Remove Whitespace at the Beginning and End
Remove Whitespace from a String

Remove Whitespace from a String

There are two common ways to remove whitespace in Java: using trim() and using replaceAll() .

Remove Whitespace at the Beginning and End

The trim() method only removes whitespace from the start and end of the string.

Example

String text = "   Java   ";
String trimmed = text.trim();
System.out.println(trimmed); // "Java"

Explanation: trim() is useful when you only want to clean up leading and trailing spaces, but it will not touch spaces inside the string.

Remove All Whitespace

If you want to remove all spaces, tabs, and newlines in a string, use replaceAll() with a regular expression.

Example

String text = "  Java \t is \n fun  ";
String noSpaces = text.replaceAll("\\s+", "");
System.out.println(noSpaces); // "Javaisfun"

Explanation: The regular expression \\s+ matches any whitespace character (spaces, tabs, newlines). Replacing them with an empty string removes all whitespace from the text.

Previous

Java How To Convert a String to an Array

Next

Java How To - Character Frequency in a String