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("^ | $|( ) ", "$1") ); }
Solution Details
Additional Resources
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3