在 Java 開發中,經常會遇到需要從單一字串中提取多個路徑的情況。例如,有一個包含多個檔案路徑、以逗號分隔的字串:
String str = "/mnt/sdcard/hehe.exe,/mnt/sdcard/GG.exe,/mnt/sdcard/oo.exe,/mnt/sdcard/aa.exe,/mnt/sdcard/qq.exe";
目標是將這五個路徑分別存入獨立的變數中,如 hehe、GG、oo、aa、qq。
split() 方法最直接且高效的做法是呼叫 String 類別的 split(String regex) 方法,以逗號 "," 作為正則表達式分隔符。該方法會返回一個字串陣列,每個元素即為一個路徑。
String[] paths = str.split(",");
接著即可透過索引取得各個路徑:
String hehe = paths[0]; // "/mnt/sdcard/hehe.exe"
String GG = paths[1]; // "/mnt/sdcard/GG.exe"
String oo = paths[2]; // "/mnt/sdcard/oo.exe"
String aa = paths[3]; // "/mnt/sdcard/aa.exe"
String qq = paths[4]; // "/mnt/sdcard/qq.exe"
trim() 或在分割後對每個元素呼叫 trim()。|、.),需轉義為 "\\|"、"\\."。Arrays.stream(str.split(",")).map(String::trim).filter(s -> !s.isEmpty()).toArray(String[]::new)。掌握 split() 這項基本技巧,能讓你在處理逗號分隔值(CSV)、路徑列表、參數解析等場景時更加得心應手。