在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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP