Removing whitespace from strings in Java

前端 未结 30 1877
一个人的身影
一个人的身影 2020-11-22 05:01

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()

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 05:41

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


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

    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.


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

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

提交回复
热议问题