Correct way to trim a string in Java

后端 未结 8 893
独厮守ぢ
独厮守ぢ 2020-12-15 04:30

In Java, I am doing this to trim a string:

String input = \" some Thing \";
System.out.println(\"before->>\"+input+\"<<-\");
input = input.trim(         


        
8条回答
  •  情歌与酒
    2020-12-15 05:02

    In theory you are not assigning a variable to itself. You are assigning the returned value of method trim() to your variable input.

    In practice trim() method implementation is optimized so that it is creating (and returning) another variable only when necessary. In other cases (when there is actually no need to trim) it is returning a reference to original string (in this case you are actually assigning a variable to itself).

    See http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String.trim%28%29

    Anyway trim() does not modify original string, so this is the right way to use it.

提交回复
热议问题