| 方法 | 說明 | 示例 |
|---|---|---|
substring(int beginIndex) | 從指定索引截取到末尾 | "abcdef".substring(2) → "cdef" |
substring(int begin, int end) | 截取 [begin, end) 區間 | "abcdef".substring(1,4) → "bcd" |
indexOf(String str) | 首次出現位置 | "a.b.c".indexOf(".") → 1 |
lastIndexOf(String str) | 最後一次出現位置 | "a.b.c".lastIndexOf(".") → 3 |
split(String regex) | 正則分割返回數組 | "a,b,c".split(",") → ["a","b","c"] |
String url = "https://wxj.videocc.net/wxj/images/2014/12/i3jwci4j.jpg";
// 取最後一個 '/' 後的內容
String fileName = url.substring(url.lastIndexOf("/") + 1);
// 結果: i3jwci4j.jpg
String fileName = "document.pdf";
String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
// 結果: pdf
String str = "user:admin,pass:123456";
// 取第一個 ':' 後到 ',' 前
int colon = str.indexOf(":");
int comma = str.indexOf(",");
String user = str.substring(colon + 1, comma);
// 結果: admin
String phone = "13812345678";
String masked = phone.substring(0, 3) + "****" + phone.substring(7);
// 結果: 138****5678
String data = "apple,banana;orange|grape";
// 正則分割:逗號、分號、竪線
String[] fruits = data.split("[,;|]");
// 結果: ["apple","banana","orange","grape"]
StringIndexOutOfBoundsExceptionsplit(".") 需寫成 split("\\."),特殊字符需雙重轉義StringBuilder 或流式處理Java 11+ 提供更豐富的 API:
// 判斷開頭/結尾
str.startsWith("prefix");
str.endsWith(".txt");
// 去除空白
str.strip(); // JDK 11+, 比 trim() 更完整支持 Unicode
// 重複字符串
"ab".repeat(3); // "ababab"
// 分割為 Stream
Arrays.stream(str.split(",")).map(String::strip).toList();