สตริงใช้เพื่อเก็บลำดับของอักขระใน Java ซึ่งถือเป็นวัตถุ คลาสสตริงของ java.lang แพ็คเกจแสดงถึงสตริง
คุณสามารถสร้างสตริงได้โดยใช้คีย์เวิร์ดใหม่ (เช่นเดียวกับออบเจ็กต์อื่นๆ) หรือโดยการกำหนดค่าให้กับตัวอักษร (เช่นประเภทข้อมูลพื้นฐานอื่นๆ)
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() - เมธอด concat() ของคลาส String ยอมรับค่า String เพิ่มลงในสตริงปัจจุบันและส่งกลับค่าที่ต่อกัน
ตัวอย่าง
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() ของคลาสเหล่านี้ยอมรับค่า String และเพิ่มไปยังวัตถุ 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