Home >Java >javaTutorial >How to Efficiently Remove Multiple Spaces from a Java String?
How to Remove Multiple Spaces from a String in Java
In Java, a common task is to clean up strings by removing extra spaces and leading or trailing whitespaces. Here's how to achieve this:
To replace multiple consecutive spaces with a single space, use the replaceAll method with a regular expression:
String mytext = " hello there "; mytext = mytext.replaceAll(" +", " ");
This regex matches one or more consecutive spaces ( ) and replaces them with a single space.
To remove leading and trailing spaces while also collapsing multiple spaces, use trim and replaceAll in combination:
String after = before.trim().replaceAll(" +", " ");
trim removes spaces at the beginning and end of the string, and replaceAll replaces multiple spaces within the string with a single space.
For more control over matching and replacing whitespace, consider using anchors and capturing groups in the provided regex example:
String[] tests = { " x ", " 1 2 3 ", "", " ", }; for (String test : tests) { System.out.format("[%s]%n", test.replaceAll("^ +| +$|( )+", "") ); }
This regex is more complex but allows for precise matching and replacement of whitespace.
The above is the detailed content of How to Efficiently Remove Multiple Spaces from a Java String?. For more information, please follow other related articles on the PHP Chinese website!