Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Substring ใน Java คืออะไร และการใช้งาน


คลาส 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 IndexInclusive (รวมตัวอักษรตำแหน่งนั้น)
End IndexExclusive (ไม่รวมตัวอักษรตำแหน่งนั้น)
LengthendIndex - beginIndex
ReturnsString ใหม่ (Original string ไม่เปลี่ยน - Immutable)
ExceptionIndexOutOfBoundsException หาก 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 แต่คืน CharSequence
  • split(String regex) - แยกสตริงเป็น Array ด้วย regex
  • charAt(int index) - ดึงตัวอักษรเดี่ยว