Home >Java >javaTutorial >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(" +", " ");
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, "");
This complex regex has three alternates:
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
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!