Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Tách chuỗi theo whitespace (khoảng trắng, tab, newline) trong Java

Dùng split("\\s+") để tách theo một hoặc nhiều ký tự whitespace (space, tab, newline, carriage return).

Regex \\s+

  • \\s = whitespace character: space, tab (\t), newline (\n), carriage return (\r), form feed (\f)
  • + = one or more (gộp nhiều whitespace liên tiếp thành 1 delimiter)

Ví dụ


import java.util.Arrays;

public class SplitWhitespace {
    public static void main(String[] args) {
        String text = "Hello\tworld\nthis\r\nis  Java";
        // \t=tab, \n=newline, \r\n=windows newline, "  "=2 spaces
        
        String[] words = text.split("\\s+");
        System.out.println(Arrays.toString(words));
    }
}

Kết quả


[Hello, world, this, is, Java]

So sánh với split(" ")


String s = "a  b\tc";
// split(" ") – chỉ tách space đơn
System.out.println(Arrays.toString(s.split(" "))); 
// [a, , b	c] – có rỗng, tab không tách

// split("\\s+") – tách mọi whitespace, gộp liên tiếp
System.out.println(Arrays.toString(s.split("\\s+"))); 
// [a, b, c] – sạch

Java 11+: String.strip() + split


// Loại bỏ leading/trailing whitespace trước khi split
String[] words = text.strip().split("\\s+");
// Tránh empty string đầu/cuối nếu text có whitespace ở rìa

Scanner – Duyệt token tự động theo whitespace


try (Scanner sc = new Scanner(text)) {
    while (sc.hasNext()) {
        System.out.println(sc.next()); // tự động split by whitespace
    }
}

⚠️ Lưu ý

  • split("\\s") (không +) → tách từng ký tự whitespace → tạo empty strings giữa 2 whitespace liên tiếp
  • split() loại bỏ trailing empty strings. Dùng split("\\s+", -1) để giữ
  • Unicode whitespace: \\s trong Java match Unicode whitespace (non-breaking space, etc.)