คลาส String ใน java.lang แทนลำดับตัวอักษร String index เริ่มจาก 0
Substring คือส่วนหนึ่งของสตริง ดึงได้ด้วยเมธอด substring() มี 2 รูปแบบ:
1. substring(int beginIndex)
คืน Substring ตั้งแต่ beginIndex ถึงท้ายสตริง
import java.util.Scanner;
public class SubStringExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
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);
}
}
Output
Enter a string: Welcome to Tutorialspoint Enter the index of the string: 11 substring = Tutorialspoint
2. substring(int beginIndex, int endIndex)
คืน Substring จาก beginIndex (inclusive) ถึง endIndex (exclusive)
import java.util.Scanner;
public class SubStringExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
String str = sc.nextLine();
System.out.println("Enter the start index: ");
int start = sc.nextInt();
System.out.println("Enter the end index: ");
int end = sc.nextInt();
String res = str.substring(start, end);
System.out.println("substring = " + res);
}
}
Output
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
รายละเอียดสำคัญ
| คุณสมบัติ | รายละเอียด |
|---|---|
| Begin Index | Inclusive (รวมตัวอักษรตำแหน่งนั้น) |
| End Index | Exclusive (ไม่รวมตัวอักษรตำแหน่งนั้น) |
| Length | endIndex - beginIndex |
| Returns | String ใหม่ (Original string ไม่เปลี่ยน - Immutable) |
| Exception | IndexOutOfBoundsException หาก index ผิด |
ตัวอย่าง Index Visualization
String s = "Hello"; // Index: 0 1 2 3 4 // Char: H e l l o s.substring(1) // "ello" (index 1 ถึงท้าย) s.substring(1, 4) // "ell" (index 1,2,3 - ไม่รวม 4) s.substring(0, 5) // "Hello" (ทั้งสตริง) s.substring(0, 0) // "" (empty string)
Java 7+ Optimization
Java 7+ ใช้ char[] sharing (substring ไม่ copy char array) แต่ Java 8+ เปลี่ยนเป็น copy ทุกครั้ง เพื่อป้องกัน Memory Leak (String เก็บ reference char[] ใหญ่)
เมธอดเกี่ยวข้อง
subSequence(int start, int end)- คล้าย substring แต่คืน CharSequencesplit(String regex)- แยกสตริงเป็น Array ด้วย regexcharAt(int index)- ดึงตัวอักษรเดี่ยว