首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 統計字符串中子串出現次數:正則與手動遍歷兩種實現

     編輯:程式設計疑難解答

需求

字符串 "csagmtacsmgtcs" 中統計 "cs" 出現次數(預期 3 次)。

方案一:正則表達式(推薦簡潔)

String str = "csagmtacsmgtcs";
Pattern p = Pattern.compile("cs");
Matcher m = p.matcher(str);
int count = 0;
while (m.find()) count++;
System.out.println(count);  // 3

注意:若子串含特殊字符(如 "c.s"),需 Pattern.quote("c.s") 轉義。

方案二:手動遍歷(無依賴、高性能)

String str = "csagmtacsmgtcs";
String target = "cs";
int count = 0;
int idx = 0;
while ((idx = str.indexOf(target, idx)) != -1) {
    count++;
    idx += target.length();  // 非重疊匹配
}
System.out.println(count);

方案三:Java 8+ Stream(函數式風格)

long count = IntStream.iterate(0, i -> i + 1)
    .limit(str.length())
    .filter(i -> str.startsWith(target, i))
    .count();

性能對比

方法時間複雜度適用場景
indexOf 循環O(n*m)簡單子串、極高性能要求
正則 MatcherO(n)複雜模式、需捕獲組
StreamO(n*m)函數式代碼風格、並行流
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved