เมธอด substring() คืน String ส่วนย่อยจากตำแหน่ง beginIndex ถึง endIndex-1 (endIndex ไม่รวม) ถ้าไม่ระบุ endIndex จะตัดถึงท้าย String Index เริ่มที่ 0
ไวยากรณ์
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
- beginIndex: ตำแหน่งเริ่มต้น (inclusive)
- endIndex: ตำแหน่งสิ้นสุด (exclusive) - ถ้าไม่ระบุ = length()
- โยน IndexOutOfBoundsException ถ้า beginIndex < 0 หรือ > length() หรือ endIndex > length() หรือ beginIndex > endIndex
ตัวอย่างโค้ด
public class StringSubstringTest {
public static void main(String[] args) {
String str = "Welcome to Tutorials Point";
System.out.println(str.substring(5)); // "me to Tutorials Point"
System.out.println(str.substring(2, 5)); // "lco" (index 2,3,4)
str.substring(6); // คืนค่าแต่ str ไม่เปลี่ยน (String immutable)
System.out.println("str value: " + str); // "Welcome to Tutorials Point"
String str1 = str.substring(5);
System.out.println("str1 value: " + str1); // "me to Tutorials Point"
}
}
ผลลัพธ์
me to Tutorials Point
lco
str value: Welcome to Tutorials Point
str1 value: me to Tutorials Point
ตัวอย่างเพิ่มเติม
String s = "Hello World";
s.substring(0, 5); // "Hello"
s.substring(6); // "World"
s.substring(6, 11); // "World"
// ตัดคำสุดท้าย
String lastWord = s.substring(s.lastIndexOf(' ') + 1); // "World"
ประสิทธิภาพ (Java 7+)
- substring() ไม่ copy char array แล้ว (ใช้ shared backing array + offset + count)
- แต่อาจ gây Memory Leak ถ้ากรอง String ใหญ่เก็บ substring เล็ก (String ใหญ่ไม่ถูก GC)
- แก้ด้วย:
new String(str.substring(...))เพื่อ force copy
เมธอดเกี่ยวข้อง
- subSequence() - คืน CharSequence (interface)
- split() - ตัดด้วย regex ได้หลายส่วน
- StringBuilder.substring() - mutable version