Home >Java >javaTutorial >How Can I Remove All Whitespace from a Java String, Including Internal Spaces?

How Can I Remove All Whitespace from a Java String, Including Internal Spaces?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 13:59:08153browse

How Can I Remove All Whitespace from a Java String, Including Internal Spaces?

Removing Whitespace from Strings in Java

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn