Removing Whitespace from Strings in Java with ReplaceAll
In Java, removing whitespace from a string can be accomplished using the replaceAll() method with the appropriate regular expression.
Problem Statement
Consider a string like "name=john age=13 year=2001" where you want to remove the whitespace between words. Using the trim() method will only remove whitespace from the beginning and end of the entire string, while using replaceAll("\W", "") will remove both whitespace and the '=' character.
Solution using replaceAll("\s ", "")
To retain the '=' character and remove all whitespace and non-visible characters (e.g., tab, n), use the following regular expression:
st.replaceAll("\s+", "")
Both replaceAll("\s ", "") and replaceAll("\s", "") will produce the same result, with the second regex being slightly faster for strings with fewer consecutive spaces. For longer consecutive spaces, the first regex performs better.
Example
To assign the modified value to a variable:
st = st.replaceAll("\s+", "");
This will result in the string "name=johnage=13year=2001" where all whitespace has been removed.
The above is the detailed content of How to Efficiently Remove Whitespace from Java Strings Using `replaceAll()`?. For more information, please follow other related articles on the PHP Chinese website!