Correct way to trim a string in Java

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

提交回复
热议问题