java.lang.String 是不可變字符序列,提供豐富實例方法。本文分類匯總高頻 API,附可運行示例代碼與輸出,適合速查與面試複習。
String s = "hello";
char[] chars = s.toCharArray(); // [h, e, l, l, o]
byte[] bytes = s.getBytes(); // UTF-8 編碼字節
String s2 = new String(chars); // 字符數組 → String
String s3 = new String(bytes, 1, 3); // 字節數組切片 → String
char c = s.charAt(1); // 'e' (索引 0 起)

int len = s.length(); // 5

String t = "abcdefgcgh";
t.indexOf("c"); // 2 (首次出現)
t.indexOf("c", 3); // 6 (從索引3開始找)
t.indexOf("x"); // -1 (不存在)

" hell o ".trim(); // "hell o" (內部空格保留)

"hello world".substring(6); // "world" (從6到末尾)
"hello world".substring(0, 5); // "hello" [0,5)

"hello world".split(" |\\t"); // ["hello", "world"] (空格或制表符)

"hello world".toUpperCase(); // "HELLO WORLD"
"HELLO WORLD".toLowerCase(); // "hello world"

"**HELLO".startsWith("**"); // true
"Hello**".endsWith("**"); // true

"HELLO".equals("hello"); // false
"HELLO".equalsIgnoreCase("hello"); // true

"hello".replaceAll("l", "x"); // "hexxo" (所有 'l' 替換)

replace、substring、concat、+)都創建新對象。大量拼接請用 StringBuilder。substring (JDK 7+) 復制底層字符數組,不再共享,避免內存洩漏。split 內部用正則,簡單分隔符(單字符)可用 StringTokenizer 或手寫解析提速。equals,比較引用用 ==。| 需求 | 方法 | 備註 |
|---|---|---|
| 字符串→字符數組 | toCharArray() | 復制數組 |
| 字符串→字節數組 | getBytes(Charset) | 指定編碼避免亂碼 |
| 獲取單字符 | charAt(index) | 越界拋 StringIndexOutOfBoundsException |
| 查找子串 | indexOf(str[, fromIndex]) | 返回 -1 表未找到 |
| 去首尾空格 | trim() | 不影響中間空格 |
| 截取子串 | substring(begin[, end]) | [begin, end) |
| 分割 | split(regex) | 正則表達式 |
| 大小寫轉換 | toUpperCase()/toLowerCase() | 區域敏感,可傳 Locale |
| 前綴判斷 | startsWith(prefix) | |
| 後綴判斷 | endsWith(suffix) | |
| 忽略大小寫比較 | equalsIgnoreCase(other) | |
| 替換所有匹配 | replaceAll(regex, replacement) | 正則替換 |
| 字面量替換 | replace(CharSequence, CharSequence) | 非正則,性能更好 |