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:
For each pattern, $1 captures the empty string (for leading/trailing spaces) or a single space (for multiple spaces in the middle).
See Also
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!