程式碼
public class CaiFen {
public static void main(String[] args) {
String str1 = "hello world";
String[] a = str1.split(" ");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]); // 修正:a[i] 而非 a[]
}
}
}
輸出結果
hello
world
原理解析
split(" ") 以**空白字元**為分隔符,將字串切成陣列 ["hello", "world"]。
System.out.println() **每次呼叫會自動換行**,因此兩個元素分行顯示。
- 若用
System.out.print() 則不會換行,輸出 helloworld。
常見陷阱
- 分隔符為正則:
split(".") 不會按點分割(點是正則萬用字元),需 split("\\.")。
- 尾部空值預設被捨棄:
"a,b,".split(",") 回傳 ["a", "b"],若需保留空字串用 split(",", -1)。
- 效能:單字元分隔可用
StringTokenizer 或手寫解析,避免正則開銷。
完整範例:多種分隔符
String data = "apple,banana;orange|grape";
String[] fruits = data.split("[,;|]"); // 字元類別:逗號、分號、管線
// 結果:["apple", "banana", "orange", "grape"]