This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Problem: Remove whitespace from Java strings

I have a string that looks like this

mysz = "name=john age=13 year=2001";
Copy the code

I want to remove the Spaces in the string. I tried using trim(), but it only removes whitespace before and after the string. I also tried (“\W”, “”), but it got rid of the = as well.

How do I make a string like this?

mysz2 = “name=johnage=13year=2001”

Answer a

The most correct answer to The question is:

String mysz2 = mysz.replaceAll("\\s"."");
Copy the code

I just got the code from the other answers. I put it up because, in addition to doing exactly what the question asks, it also shows that the result is returned as a new string, and that the source string has not been modified like the other code

(Seasoned Java developers might say, “Of course, you can’t really modify a string,” but the intended audience might not be too aware of this.)

Answer two

St. replaceAll (” \ s + “, “”) clear all of the Spaces and the invisible characters (such as TAB, \ n).

St. replaceAll (” \ s + “, “”) and st. replaceAll (” \ s”, “”) effect is the same

The second regular expression is about 20% faster than the first, but as the number of Spaces increases, the first one may outperform the second

Assign this value to a variable if you don’t use it directly st = st.replaceAll(“\s+”,””)

Answer two

replaceAll("\\s"."")
Copy the code

\w = all word characters

\W = All non-word characters (including various punctuation marks)

\s = Any whitespace characters (including Spaces, tabs, etc.)

\S = Any non-white space character (including alphanumeric punctuation marks etc.)

(As pointed out above, if you want \s to reach the regular expression engine, you need to escape the character, so write \s.)

The article translated from Stack Overflow:stackoverflow.com/questions/5…