如何在Java中混合兩個字串並生成另一個字串?


字串用於在Java中儲存字元序列,它們被視為物件。java.lang包的String類表示一個字串。

您可以使用new關鍵字(像任何其他物件一樣)或透過為文字賦值(像任何其他原始資料型別一樣)來建立一個字串。

String stringObject = new String("Hello how are you");
String stringLiteral = "Welcome to Tutorialspoint";

連線字串

您可以透過以下方式在Java中連線字串:

使用“+”運算子 - Java提供了一個連線運算子,使用它,您可以直接新增兩個字串文字

示例

import java.util.Scanner;
public class StringExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the first string: ");
      String str1 = sc.next();
      System.out.println("Enter the second string: ");
      String str2 = sc.next();
      //Concatenating the two Strings
      String result = str1+str2;
      System.out.println(result);
   }
}

輸出

Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap
Java

使用concat()方法 - String類的concat()方法接受一個字串值,將其新增到當前字串並返回連線後的值。

示例

import java.util.Scanner;
public class StringExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the first string: ");
      String str1 = sc.next();
      System.out.println("Enter the second string: ");
      String str2 = sc.next();
      //Concatenating the two Strings
      String result = str1.concat(str2);
      System.out.println(result);
   }
}

輸出

Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap

使用StringBuffer和StringBuilder類 - 當需要修改時,StringBuffer和StringBuilder類可以用作String的替代品。

它們與String類似,只是它們是可變的。它們提供了各種內容操作方法。這些類的append()方法接受一個字串值並將其新增到當前StringBuilder物件。

示例

import java.util.Scanner;
public class StringExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the first string: ");
      String str1 = sc.next();
      System.out.println("Enter the second string: ");
      String str2 = sc.next();
      StringBuilder sb = new StringBuilder(str1);
      //Concatenating the two Strings
      sb.append(str2);
      System.out.println(sb);
   }
}

輸出

Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap

更新於:2019年10月10日

14K+瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.