首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

Java String 類核心方法大全:轉換、查找、截取、分割、替換與比較實戰

     編輯:關於C++

java.lang.String 是不可變字符序列,提供豐富實例方法。本文分類匯總高頻 API,附可運行示例代碼與輸出,適合速查與面試複習。

1. 字符串與字符/字節數組互轉

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
toCharArray輸出 getBytes輸出

2. 單字符訪問

char c = s.charAt(1);  // 'e' (索引 0 起)
charAt輸出

3. 長度獲取

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

4. 查找與索引


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

5. 去除首尾空白


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

6. 子串截取


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

7. 正則分割


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

8. 大小寫轉換


"hello world".toUpperCase();  // "HELLO WORLD"
"HELLO WORLD".toLowerCase();  // "hello world"
大小寫輸出

9. 前綴/後綴判斷


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

10. 忽略大小寫比較


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

11. 字符串替換


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

性能與最佳實踐提示

  • 不可變性:每次修改操作(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)非正則,性能更好
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved