java中concat()方法的使用說明
阿新 • • 發佈:2020-08-25
concat()方法介紹:
將幾個字串連線到一起。
例如:
s = s.concat(str1);//將字串str1接到字串s後面
s = s.concat(str2);//將字串str1接到字串s後面
程式碼:
public class Test { public static void main(String[] args){ String s = "厲害了,"; String str1 = "我的"; String str2 = "國!"; s = s.concat(str1);//將字串str1接到字串s後面 s = s.concat(str2);//將字串str1接到字串s後面 System.out.println(s); } }
執行結果:
厲害了,我的國!
補充知識:Java| String 字串拼接方法 concat 和 + 效率比較
測試程式碼:
public static void main(String[] args) { String str1 = "yveshe"; String str2 = "hello"; /** * concat */ System.gc(); long startTime1 = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { str1 = str1.concat(str2); } long endTime1 = System.currentTimeMillis(); System.out.println("concat:" + (endTime1 - startTime1)); /** * + */ str1 = "yveshe"; System.gc(); long startTime2 = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { str1 = str1 + str2; } long endTime2 = System.currentTimeMillis(); System.out.println("+: " + (endTime2 - startTime2)); }
測試結果:
concat:231
+: 468
總結:
1.concat的計算效率要比+的效率高
2.concat只適用於string和string的拼接,+適用於string和任何物件的拼接
3.當在少量的資料拼接時,使用concat和+都行,如果是大量的資料拼接,建議使用StringBuilder或者StringBuffer.
以上這篇java中concat()方法的使用說明就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。