假设我们有以下字符串。
String str = "Learning never ends! Learning never stops!";
在上面的字符串中,我们需要找出“学习”子字符串出现了多少次。
为此,循环直到索引不等于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!