Java String split()

split() 方法用來將字串分割成陣列。

語法

string.split(String regex)
string.split(String regex, int limit)
  • regex:分隔符號(正規表達式)
  • limit:分割的最大數量
  • 回傳:字串陣列

基本範例

String s = "apple,banana,cherry";

String[] fruits = s.split(",");

for (String fruit : fruits) {
    System.out.println(fruit);
}
// apple
// banana
// cherry

System.out.println(fruits.length);  // 3

常見分隔符號

// 逗號分隔
"a,b,c".split(",");  // ["a", "b", "c"]

// 空白分隔
"a b c".split(" ");  // ["a", "b", "c"]

// 多個空白
"a  b  c".split("\\s+");  // ["a", "b", "c"]

// 換行分隔
"a\nb\nc".split("\n");  // ["a", "b", "c"]

// 多種分隔符號
"a,b;c:d".split("[,;:]");  // ["a", "b", "c", "d"]

特殊字元需要跳脫

某些字元在正規表達式中有特殊意義,需要跳脫:

// . 在正規表達式中代表任意字元
String s = "a.b.c";
// String[] parts = s.split(".");  // 錯誤!結果是空陣列

// 正確的方式
String[] parts1 = s.split("\\.");     // ["a", "b", "c"]
String[] parts2 = s.split("[.]");      // ["a", "b", "c"]
String[] parts3 = s.split(Pattern.quote("."));  // ["a", "b", "c"]

需要跳脫的特殊字元:. * + ? ^ $ { } [ ] ( ) | \

// 分割管道符號
"a|b|c".split("\\|");  // ["a", "b", "c"]

// 分割反斜線
"a\\b\\c".split("\\\\");  // ["a", "b", "c"]

limit 參數

控制分割的最大數量:

String s = "a,b,c,d,e";

String[] parts1 = s.split(",", 2);
// ["a", "b,c,d,e"](最多分成 2 份)

String[] parts2 = s.split(",", 3);
// ["a", "b", "c,d,e"](最多分成 3 份)

String[] parts3 = s.split(",", -1);
// 保留結尾的空字串

結尾空字串

String s = "a,b,c,,,";

String[] parts1 = s.split(",");
// ["a", "b", "c"](預設會移除結尾空字串)

String[] parts2 = s.split(",", -1);
// ["a", "b", "c", "", "", ""](保留所有)

實際應用

解析 CSV

String csv = "Alice,25,taipei";
String[] data = csv.split(",");

String name = data[0];   // "Alice"
int age = Integer.parseInt(data[1]);  // 25
String city = data[2];   // "taipei"

解析路徑

String path = "/home/user/documents/file.txt";
String[] parts = path.split("/");

// ["", "home", "user", "documents", "file.txt"]
String filename = parts[parts.length - 1];  // "file.txt"

解析查詢字串

String query = "name=Alice&age=25&city=taipei";
String[] params = query.split("&");

for (String param : params) {
    String[] keyValue = param.split("=");
    System.out.println(keyValue[0] + " = " + keyValue[1]);
}
// name = Alice
// age = 25
// city = taipei

按行分割

String text = "Line 1\nLine 2\nLine 3";

// 方式一
String[] lines = text.split("\n");

// 方式二(處理不同系統的換行)
String[] lines2 = text.split("\\r?\\n");

// 方式三(Java 11+)
String[] lines3 = text.lines().toArray(String[]::new);

join():相反操作

使用 String.join() 將陣列合併成字串:

String[] fruits = {"apple", "banana", "cherry"};

String result = String.join(",", fruits);
System.out.println(result);  // "apple,banana,cherry"

String result2 = String.join(" - ", fruits);
System.out.println(result2);  // "apple - banana - cherry"