Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

java - 在Java中从字符串中删除空格(Removing whitespace from strings in Java)

I have a string like this:

(我有一个像这样的字符串:)

mysz = "name=john age=13 year=2001";

I want to remove the whitespaces in the string.

(我想删除字符串中的空格。)

I tried trim() but this removes only whitespaces before and after the whole string.

(我试过trim()但这只删除了整个字符串前后的空格。)

I also tried replaceAll("\\W", "") but then the = also gets removed.

(我也尝试了replaceAll("\\W", "")但是=也被删除了。)

How can I achieve a string with:

(如何使用以下方法实现字符串:)

mysz2 = "name=johnage=13year=2001"
  ask by zyamat translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

st.replaceAll("\\s+","") removes all whitespaces and non-visible characters (eg, tab, \n ).

(st.replaceAll("\\s+","")删除所有空格和不可见字符(例如,tab, \n )。)


st.replaceAll("\\s+","") and st.replaceAll("\\s","") produce the same result.

(st.replaceAll("\\s+","")st.replaceAll("\\s","")产生相同的结果。)

The second regex is 20% faster than the first one, but as the number consecutive spaces increases, the first one performs better than the second one.

(第二个正则表达式比第一个正则表达式快20%,但是随着连续空格数量的增加,第一个正则表达式的性能要好于第二个正则表达式。)


Assign the value to a variable, if not used directly:

(将值分配给变量(如果不直接使用):)

st = st.replaceAll("\s+","")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...