Java: Replacing Multiple Spaces with Single Space and Trimming Leading and Trailing Spaces
To address the task of reducing multiple spaces to a single space and eliminating leading and trailing spaces, we have several Java solutions.
Solution 1: Using trim() and replaceAll()
This solution utilizes the trim() method to remove the leading and trailing spaces, followed by replaceAll() to combine multiple spaces into a single space:
String after = before.trim().replaceAll(" +", " ");
Solution 2: Regex-only
While less readable, it's feasible to resolve the problem with a single replaceAll() utilizing a complex regular expression:
String[] tests = { " x ", " 1 2 3 ", "", " ", }; for (String test : tests) { System.out.format("[%s]%n", test.replaceAll("^ +| +$|( )+", "") ); }
Solution Details
Additional Resources
The above is the detailed content of How Can I Efficiently Remove Multiple Spaces and Trim Leading/Trailing Spaces in Java?. For more information, please follow other related articles on the PHP Chinese website!