String s = "Hello 世界";
s.length(); // 9 (字元數,非位元組)
s.charAt(3); // 'l'
s.codePointAt(6); // 19990 ('世' 的 Unicode 碼點)
"abc".equals("abc"); // true 內容比較
"abc".equalsIgnoreCase("ABC"); // true 忽略大小寫
"abc".compareTo("abd"); // -1 字典序比較
"abc".startsWith("ab"); // true
"abc".endsWith("bc"); // true
"".isEmpty(); // true (Java 6+)
" ".isBlank(); // true (Java 11+)
"hello world".indexOf("o"); // 4
"hello world".lastIndexOf("o"); // 7
"hello world".indexOf("o", 5); // 7 (從索引 5 開始找)
"hello world".substring(6); // "world"
"hello world".substring(0, 5); // "hello"
"a,b,c".split(","); // ["a","b","c"]
"a,b,c".split(",", 2); // ["a", "b,c"] 限制分割數
"hello".replace('l', 'L'); // "heLLo" 字元替換
"hello".replace("ll", "LL"); // "heLLo" 字串替換
"hello".replaceAll("[aeiou]", "*"); // "h*ll*" 正則替換
"hello".replaceFirst("[aeiou]", "*"); // "h*llo" 僅首次
" abc ".trim(); // "abc" 去首尾空白 (Java 11+ strip())
"ABC".toLowerCase(); // "abc"
"abc".toUpperCase(); // "ABC"
String.format("Hi %s, age %d", "Tom", 18); // "Hi Tom, age 18"
String.join("-", "2024", "01", "01"); // "2024-01-01" (Java 8+)
// 高效拼接
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) sb.append(i);
String result = sb.toString();
String.valueOf(123); // "123"
Integer.parseInt("123"); // 123
Double.parseDouble("3.14"); // 3.14
new String(new byte[]{65,66}, StandardCharsets.UTF_8); // "AB"
"AB".getBytes(StandardCharsets.UTF_8); // byte[]
| 場景 | 推薦做法 | 避免 |
|---|---|---|
| 循環/大量拼接 | StringBuilder (單執行緒) / StringBuffer (多執行緒) | + 操作符 |
| 固定模板格式化 | String.format / MessageFormat | 手工拼接 |
| 正則分割/替換 | 預編譯 Pattern 重複使用 | 每次呼叫 split/replaceAll |
| 字串比較 | equals / Objects.equals (防 NPE) | == (比較參考) |
// 陷阱 1:substring 共享底層 char[] (Java 7u6 前)
// 解決:new String(s.substring(...)) 強制複製
// 陷阱 2:split 尾部空字串被丟棄
"a,b,".split(","); // ["a", "b"] 長度 2
"a,b,".split(",", -1); // ["a", "b", ""] 長度 3 保留尾部
// 陷阱 3:正則特殊字元
"1.2.3".split("."); // [] 空陣列!. 是正則元字元
"1.2.3".split("\\."); // ["1","2","3"] 需雙重轉義
" abc ".strip(); // "abc" (支援 Unicode 空白字元) "abc".stripLeading(); // "abc" "abc".stripTrailing(); // "abc" "abc".isBlank(); // false " ".isBlank(); // true "abc".repeat(3); // "abcabcabc" "abc\n123".lines().collect(Collectors.toList()); // ["abc", "123"]
字串處理看似基礎,但細節決定效能與正確性。熟記核心 API、善用 `StringBuilder`、警惕正則陷阱,是寫出健壯 Java 程式碼的基本功。