在 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!
广告