Home >Java >javaTutorial >How Can I Remove All Whitespace from a Java String, Including Internal Spaces?
In Java, the trim() method conveniently trims leading and trailing whitespace characters from a string. However, when dealing with strings containing internal whitespace that you wish to eliminate, this method falls short.
To effectively remove all whitespace, including those between words, consider utilizing the replaceAll() method with an appropriate regular expression. The following expression replaces contiguous whitespace characters with an empty string:
st.replaceAll("\s+", "");
This expression matches one or more whitespace characters (s) in a row and replaces them with nothing. Alternatively, you could use the following expression:
st.replaceAll("\s", "");
This expression accomplishes the same outcome but is slightly less efficient when dealing with multiple consecutive spaces.
Here's an example:
String mystz = "name=john age=13 year=2001"; String mystz2 = mystz.replaceAll("\s+", "");
After this operation, mystz2 will contain the following value:
name=johnage=13year=2001
The above is the detailed content of How Can I Remove All Whitespace from a Java String, Including Internal Spaces?. For more information, please follow other related articles on the PHP Chinese website!