Home > Java > javaTutorial > How to Efficiently Remove Multiple, Leading, and Trailing Spaces from Java Strings?

How to Efficiently Remove Multiple, Leading, and Trailing Spaces from Java Strings?

Patricia Arquette
Release: 2024-11-25 17:57:12
Original
739 people have browsed it

How to Efficiently Remove Multiple, Leading, and Trailing Spaces from Java Strings?

Eliminating Multiple Spaces and Leading/Trailing Whitespace in Java Strings

In Java, you may encounter strings containing multiple consecutive spaces and unnecessary whitespace at the beginning or end. To resolve this, you seek an efficient approach to replace all multiple spaces with a single space while simultaneously eliminating leading and trailing spaces.

Solution with trim() and replaceAll()

The recommended solution combines the trim() method with the replaceAll() method:

String after = before.trim().replaceAll(" +", " ");
Copy after login

trim() removes all leading and trailing whitespace from the given string. Then, replaceAll() replaces all occurrences of two or more consecutive spaces with a single space.

No trim() regex solution

While less readable, it is possible to achieve the same outcome with a single replaceAll():

String pattern = "^ +| +$|( )+";
String after = before.replaceAll(pattern, "");
Copy after login

This complex regex has three alternates:

  • ^ : 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 in the middle of the string

In all cases, it replaces the matched sequence with $1, capturing a single space in place of multiple spaces or eliminating them altogether if at the beginning or end.

Additional Resources

  • String.trim(): https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()
  • Regular Expressions for Repetition: https://regular-expressions.info/Repetition
  • Regular Expressions for Anchors: https://regular-expressions.info/Anchors

The above is the detailed content of How to Efficiently Remove Multiple, Leading, and Trailing Spaces from Java Strings?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template