Removing whitespace from strings in Java

前端 未结 30 1886
一个人的身影
一个人的身影 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:47

    The most correct answer to the question is:

    String mysz2 = mysz.replaceAll("\\s","");
    

    I just adapted this code from the other answers. I'm posting it because besides being exactly what the question requested, it also demonstrates that the result is returned as a new string, the original string is not modified as some of the answers sort of imply.

    (Experienced Java developers might say "of course, you can't actually modify a String", but the target audience for this question may well not know this.)

提交回复
热议问题