สตริง คลาสของแพ็คเกจ java.lang แสดงถึงชุดของอักขระ ตัวอักษรสตริงทั้งหมดในโปรแกรม Java เช่น "abc" ถูกนำมาใช้เป็นอินสแตนซ์ของคลาสนี้ ดัชนีสตริงคือจำนวนเต็มที่แสดงตำแหน่งของอักขระแต่ละตัวในสตริงโดยเริ่มจากศูนย์
สตริงย่อย เป็นส่วน/ส่วนของสตริง คุณสามารถระบุสตริงย่อยของสตริงได้โดยใช้ substring() วิธีการของคลาสสตริง วิธีการนี้มีสองรูปแบบ -
สตริงย่อย (int startIndex)
เมธอดนี้ยอมรับค่าจำนวนเต็มที่แทนดัชนีในสตริงปัจจุบัน และส่งกลับสตริงย่อยที่เริ่มต้นจากดัชนีที่กำหนดไปยังจุดสิ้นสุดของสตริง
ตัวอย่าง
import java.util.Scanner;
public class SubStringExample {
public static void main(String[] args) {
System.out.println("Enter a string: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println("Enter the index of the substring: ");
int index = sc.nextInt();
String res = str.substring(index);
System.out.println("substring = " + res);
}
} ผลลัพธ์
Enter a string: Welcome to Tutorialspoint Enter the index of the string: 11 substring = Tutorialspoint
สตริงย่อย (int startIndex, int endstring)
เมธอดนี้ยอมรับค่าจำนวนเต็มสองค่าที่แสดงค่าดัชนีของสตริงปัจจุบันและส่งคืนสตริงย่อยระหว่างค่าดัชนีที่กำหนด
ตัวอย่าง
import java.util.Scanner;
public class SubStringExample {
public static void main(String[] args) {
System.out.println("Enter a string: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println("Enter the start index of the substring: ");
int start = sc.nextInt();
System.out.println("Enter the end index of the substring: ");
int end = sc.nextInt();
String res = str.substring(start, end);
System.out.println("substring = " + res);
}
} ผลลัพธ์
Enter a string: hello how are you welcome to Tutorialspoint Enter the start index of the substring: 10 Enter the end index of the substring: 20 substring = are you we