Correct way to trim a string in Java

后端 未结 8 858
独厮守ぢ
独厮守ぢ 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.

    0 讨论(0)
  • 2020-12-15 05:03

    The traditional approach is to use the trim method inline...for example:

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

    If it is a string that should be trimmed for all usages, trim it up front like you have done. Re-using the same memory location like you have done is not a bad idea, if you want to communicate your intent to other developers. When writing in Java, memory managment is not they key issue since the "gift" of Java is that you do not need to manage it.

    0 讨论(0)
提交回复
热议问题