在 Java 中統計子字串在大字串中出現的次數
假設我們有以下字串。
String str = "Learning never ends! Learning never stops!";
在上文中,我們需要找出子字串"Learning" 出現的次數。
為此,迴圈,直到索引不等於 1,並計算。
while ((index = str.indexOf(subString, index)) != -1) { subStrCount++; index = index + subString.length(); }
以下是一個示例。
示例
public class Demo { public static void main(String[] args) { String str = "Learning never ends! Learning never stops!"; System.out.println("String: "+str); int subStrCount = 0; String subString = "Learning"; int index = 0; while ((index = str.indexOf(subString, index)) != -1) { subStrCount++; index = index + subString.length(); } System.out.println("Substring "+subString+" found "+subStrCount+" times!"); } }
輸出
String: Learning never ends! Learning never stops! Substring Learning found 2 times!
廣告