String s = "TEST";
String s2 = s.trim();
s.concat("ING");
System.out.println("S = "+s);
System.out.println("S2 = "+s2);
結果輸出:
S = TEST
S2 = TEST
BUILD SUCCESSFUL (total time: 0 seconds)
爲什麼 「TEST」 和 「ING」 不連接在一起?
String s = "TEST";
String s2 = s.trim();
s.concat("ING");
System.out.println("S = "+s);
System.out.println("S2 = "+s2);
結果輸出:
S = TEST
S2 = TEST
BUILD SUCCESSFUL (total time: 0 seconds)
爲什麼 「TEST」 和 「ING」 不連接在一起?
一個String是immutable,這意味着你不能改變在Java中的String。 concat()返回一個新的連接字符串。
String s = "TEST";
String s2 = s.trim();
String s3 = s.concat("ING");
System.out.println("S = "+s);
System.out.println("S2 = "+s2);
System.out.println("S3 = "+s3);
謝謝..我的疑問得到澄清.. :) – 2010-05-12 12:43:35
@soma sekhar,如果這個答案解決了你的問題,你應該接受它。 – 2010-05-12 13:17:55
因爲String
是不可變的 - 類String
不包含更改String
對象本身內容的方法。 concat()
方法返回一個新的String
,其中包含操作的結果。取而代之的是:
s.concat("ING");
試試這個:
s = s.concat("ING");
yup ..以這種方式工作..thanku .. – 2010-05-12 12:45:17
我想你想要做的是:
s2 = s.concat("ING");
concat函數不改變字符串s,它只是返回s的附加參數。
concat
返回一個字符串,所以你基本上調用concat而不存儲它返回的內容。 嘗試此:
String s = "Hello";
String str = s.concat(" World");
System.out.println(s);
System.out.println(str);
應該打印:
Hello
Hello World
作爲字符串是不可變時的concat()被調用的任何字符串OBJ中
的String = 「ABC」; 新的String obj被創建在字符串pool ref由s
s = s.concat(「def」); 這裏有一個字符串obj與val abcdef被創建和引用s
.concat()
方法返回新的連接值。 那裏你做了s.concat("ING")
- >這給了返回值「測試」。但是你必須在聲明的變量中接收它。
如果你沒有s=s.concat("ING");
則「S」值將變爲「測試」
鏈接到文檔:http://java.sun.com/j2se/1.4.2/docs/api/java/ lang/String.html#concat%28java.lang.String%29 – 2010-05-12 12:44:23
'trim()'不會做任何事情。 – shmosel 2018-02-23 18:49:15