Home > Java > javaTutorial > How to Efficiently Remove Whitespace from Java Strings Using `replaceAll()`?

How to Efficiently Remove Whitespace from Java Strings Using `replaceAll()`?

Linda Hamilton
Release: 2024-12-13 03:34:14
Original
868 people have browsed it

How to Efficiently Remove Whitespace from Java Strings Using `replaceAll()`?

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

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

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!

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