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

Java String.substring 用法全攻略:截取、刪除、邊界處理

     編輯:Java 相關知識

兩個重載方法簽名

String substring(int beginIndex)           // 從 beginIndex 截取到末尾
String substring(int beginIndex, int endIndex) // 截取 [beginIndex, endIndex) 左閉右開區間

基礎示例

"1234567890abcdefgh".substring(10)    // "abcdefgh"
"1234567890abcdefgh".substring(0, 9)  // "123456789"

實戰場景:刪除指定子串

public static String removeSubstring(String source, String target) {
    if (source == null || target == null || target.isEmpty()) return source;

    if (source.startsWith(target)) {
        return source.substring(target.length());
    }
    if (source.endsWith(target)) {
        return source.substring(0, source.length() - target.length());
    }
    int idx = source.indexOf(target);
    if (idx >= 0) {
        return source.substring(0, idx) + source.substring(idx + target.length());
    }
    return source; // 未找到
}

// 測試
String s = "this is my original string";
System.out.println(removeSubstring(s, " original")); // "this is my string"

內存洩漏陷阱 (JDK 6/7) 及現狀

  • JDK 6/7:substring 共享底層 char[],長字符串截取小片段導致大數組無法 GC;
  • JDK 7u6+ / JDK 8+:substring **複製新數組**,徹底解決洩漏;
  • 若維護舊版本項目,手動 new String(str.substring(...)) 強制複製。

邊界情況速查表

調用結果異常
s.substring(0)原字符串無
s.substring(s.length())""無
s.substring(-1)—StringIndexOutOfBoundsException
s.substring(0, s.length()+1)—StringIndexOutOfBoundsException
s.substring(5, 3)—StringIndexOutOfBoundsException

性能提示

  • 截取操作 O(長度) 時間/空間 (JDK 8+);
  • 高頻熱點路徑考慮 char[]/StringBuilder 手動操作避免分配;
  • 正則分割 split() 內部同樣創建大量子串,大數據量慎用。

掌握 substring 的語義、版本差異與邊界條件,是 Java 字符串處理的基本功。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved