繁体   English   中英

a = a.trim()和a.trim()之间有什么区别?

[英]What is the difference between a = a.trim() and a.trim()?

我遇到了一点混乱。

知道 String对象是不可变的 这意味着如果我从String类调用一个方法,比如replace()那么String的原始内容不会改变。 相反,将根据原始String返回新的 String 但是,可以为同一变量分配新值。

基于这个理论,我总是写a = a.trim() ,其中a是一个String 一切都很好,直到我的老师告诉我,也可以使用a.trim() 这搞砸了我的理论。

我和老师一起测试了我的理论。 我使用了以下代码:

String a = "    example   ";
System.out.println(a);
a.trim();      //my teacher's code.
System.out.println(a);
a = "    example   ";
a = a.trim();  //my code.
System.out.println(a);

我得到以下输出:

    example   
    example   
example

当我向老师指出时,她说,

这是因为我使用的是较新版本的Java(jdk1.7),而a.trim()适用于以前的Java版本。

请告诉我谁有正确的理论,因为我完全不知道

字符串在java中是不可变的。 trim()返回一个新字符串,所以你必须通过赋值来获取它。

    String a = "    example   ";
    System.out.println(a);
    a.trim();      // String trimmed.
    System.out.println(a);// still old string as it is declared.
    a = "    example   ";
    a = a.trim();  //got the returned string, now a is new String returned ny trim()
    System.out.println(a);// new string

编辑:

她说这是因为我使用的是较新版本的java(jdk1.7),而a.trim()在以前版本的java中有效。

请找一位新的java老师。 这完全是一个没有证据的虚假陈述。

字符串是不可变的,对它的任何更改都将创建一个新字符串。 如果要使用trim方法返回的字符串更新引用,则需要使用该赋值。 所以这应该用于:

a = a.trim()

简单地使用“a.trim()”可能会在内存中修剪它(或者智能编译器会完全抛出表达式),但结果不会存储,除非您先将其分配给变量,如“a = a.trim” ();”

如果要对字符串进行某些操作(例如修剪),则必须将字符串值存储在相同或不同的变量中。

String a = "    example   ";
System.out.println(a);
a.trim();      //output new String is not stored in any variable
System.out.println(a); //This is not trimmed
a = "    example   ";
a = a.trim();  //output new String is  stored in a variable
System.out.println(a); //As trimmed value stored in same a variable it will print "example"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM