Java 中的字串連線


在 Java 中,可以用 concat() 方法或使用“+”(連線運算子)連線兩個字串。

concat() 方法

concat() 方法將一個字串追加到另一個字串末尾。此方法返回一個字串,其值為傳入該方法的字串追加到呼叫此方法的字串末尾後的結果。

示例

public class ConncatSample {
   public static void main(String []args) {
      String s1 = "Hello";
      String s2 = "world";
      String res = s1.concat(s2);
      System.out.print("Concatenation result:: ");
      System.out.println(res);
   }
}

輸出

Concatenation result:: Helloworld

“+”運算子

與 concat 方法一樣,“+”運算子對給定的運算元也執行連線操作。

示例

public class ConncatSample {
   public static void main(String []args) {
      String s1 = "Hello";
      String s2 = "world";
      String res = s1+s2;
      System.out.print("Concatenation result:: ");
      System.out.println(res);
   }
}

輸出

Concatenation result:: Helloworld

更新時間: 2020 年 2 月 26 日

574 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.