Java计算子字符串在字符串中出现的次数

时间:2024-12-13 21:32:36
public class Demo { public static void main(String[] args) { String str = "HelloHello HelloHello World Hello China Hello Tomorrow"; // 匹配的子串在字符串中的下标 int index = 0; // 计算出现的次数 int count = 0; String findStr = "Hello"; while((index = str.indexOf(findStr, index)) != -1) { (str.charAt(index) + " "); index += (); count++; } (count); } }// out: H H H H H H 6