Home  >  Article  >  Java  >  How Can I Remove Multiple Spaces and Leading/Trailing Whitespace in Java?

How Can I Remove Multiple Spaces and Leading/Trailing Whitespace in Java?

Susan Sarandon
Susan SarandonOriginal
2024-11-25 08:47:14213browse

How Can I Remove Multiple Spaces and Leading/Trailing Whitespace in Java?

Removing Multiple Spaces and Leading/Trailing Whitespace in Java

When working with strings in Java, it's often necessary to manipulate whitespace to improve readability and consistency. One common task is replacing multiple spaces with a single space while also removing spaces at the beginning and end of a string.

Let's start with a classic example: converting " hello there " to "hello there."

Using trim() and replaceAll()

A straightforward approach involves combining the trim() and replaceAll() methods:

String before = " hello     there   ";
String after = before.trim().replaceAll(" +", " ");

The trim() method removes all leading and trailing whitespace, while replaceAll() replaces multiple consecutive spaces (" ") with a single space.

Regex-Only Solution

It's also possible to accomplish this with a single replaceAll using regular expressions:

String result = before.replaceAll("^ +| +$|( )+", "");

This regex has three alternate patterns:

  • "^ ": Matches any sequence of spaces at the beginning of the string
  • " $": Matches any sequence of spaces at the end of the string
  • "( ) ": Matches any sequence of spaces that matches neither of the above (i.e., multiple spaces in the middle)

For each pattern, $1 captures the empty string (for leading/trailing spaces) or a single space (for multiple spaces in the middle).

See Also

  • String.trim() for more information on removing whitespace
  • regular-expressions.info/Repetition for details on regex repetition patterns
  • regular-expressions.info/Anchors for information on regex anchors

The above is the detailed content of How Can I Remove Multiple Spaces and Leading/Trailing Whitespace in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn