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
Release: 2024-12-20 13:59:08
Original
157 people have browsed it

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+", "");
Copy after login

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", "");
Copy after login

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+", "");
Copy after login

After this operation, mystz2 will contain the following value:

name=johnage=13year=2001
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template