Home >Java >javaTutorial >How Can I Clean Up Whitespace in a Java String by Replacing Multiple Spaces with Single Spaces and Removing Leading/Trailing Spaces?
When working with strings in Java, it is often necessary to clean up whitespace. This includes removing leading and trailing spaces, as well as replacing multiple consecutive spaces with a single space.
To replace two or more spaces with a single space and delete leading and trailing spaces in Java, the following steps can be taken:
Replace Multiple Spaces with a Single Space: Use the replaceAll() method with the following regular expression:
" +| "
This expression matches either two or more spaces (" ") or a single space (" ") and replaces it with a single space.
Using these steps, the following code can be used to convert a string with multiple spaces to a string with a single space:
String mytext = " hello there "; String after = mytext.trim().replaceAll(" +| ", " "); System.out.println(after); // Output: hello there
No trim() Regex:
While the trim() solution is more readable, it is also possible to achieve the desired result using a single replaceAll() method with a more complex regular expression:
String after = mytext.replaceAll("^ +| +$|( )+", "");
See Also:
The above is the detailed content of How Can I Clean Up Whitespace in a Java String by Replacing Multiple Spaces with Single Spaces and Removing Leading/Trailing Spaces?. For more information, please follow other related articles on the PHP Chinese website!