เมธอด split(String regex) แยกสตริงตาม delimiter (regex) คืนค่า String array
Split ด้วย Space เดียว (Basic)
String str = "Hello how are you";
String[] parts = str.split(" "); // split by single space
// [Hello, how, are, you]
ปัญหา: Multiple Spaces / Tabs / Newlines
String str = "Hello how\tare\nyou";
// split(" ") -> [Hello, , , how, are, you] // มี empty strings!
วิธีที่ถูกต้อง: ใช้ Regex \\s+
\\s = whitespace character (space, tab \t, newline \n, carriage return \r, form feed \f)
+ = one or more
String str = "Hello how\tare\nyou";
String[] parts = str.split("\\s+");
// [Hello, how, are, you] - ไม่มี empty strings
ตัวอย่างโค้ดครบถ้วน
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class SplitWhitespace {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("D:\\sample.txt"));
StringBuilder sb = new StringBuilder();
while (sc.hasNextLine()) {
sb.append(sc.nextLine()).append("\n");
}
String source = sb.toString();
String[] result = source.split("\\s+");
for (String s : result) {
System.out.println(s);
}
}
}
ผลลัพธ์
Hello
how
are
you
วิธีทางเลือก: ใช้ Scanner โดยตรง
Scanner ใช้ delimiter pattern (default = \\s+) แล้ว
Scanner sc = new Scanner(new File("file.txt"));
while (sc.hasNext()) {
String token = sc.next(); // ได้ token แยกด้วย whitespace แล้ว
System.out.println(token);
}
วิธีทางเลือก: StringTokenizer (Legacy)
StringTokenizer st = new StringTokenizer(str); // default delimiter = whitespace
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
การเปรียบเทียบ
| วิธี | Multiple Whitespace | Tab/Newline | Empty Tokens | Performance |
|---|---|---|---|---|
| split(" ") | ✗ (สร้าง empty) | ✗ | มี | เร็ว |
| split("\\s+") | ✓ | ✓ | ไม่มี | เร็ว |
| Scanner.next() | ✓ | ✓ | ไม่มี | ปานกลาง |
| StringTokenizer | ✓ | ✓ | ไม่มี | ช้า (legacy) |
ข้อควรระวัง
split("\\s+")บน string ที่เริ่ม/จบด้วย whitespace จะไม่สร้าง empty token นำหน้า/ท้ายsplit("\\s+", -1)จะเก็บ trailing empty strings (หากมี)- Pre-compile Pattern:
Pattern.compile("\\s+").split(str)หากทำบ่อย - Java 11+:
String.strip()ลบ whitespace นำหน้า/ท้าย ก่อน split
สรุป
แนะนำ: str.split("\\s+") - มาตรฐาน เร็ว จัดการ whitespace ทุกชนิดได้ถูกต้อง