可以使用String类的indexOf()方法和substring()方法来查询字符串出现的次数。
下面是一个示例代码:
public class CountOccurrences { public static int countOccurrences(String str, String target) { int count = 0; int index = 0; while ((index = str.indexOf(target, index)) != -1) { count++; index += target.length(); } return count; } public static void main(String[] args) { String str = "Hello Hello Hello World"; String target = "Hello"; int count = countOccurrences(str, target); System.out.println("字符串 \"" + target + "\" 出现的次数为: " + count); } }
运行以上代码,输出结果为:
字符串 "Hello" 出现的次数为: 3
在上面的代码中,我们定义了一个countOccurrences()方法,该方法接收两个参数:待查询的字符串str和目标字符串target。在方法内部,我们使用while循环来查找目标字符串在待查询字符串中的出现次数。我们通过调用indexOf()方法来获取目标字符串在待查询字符串中的索引,如果返回值不为-1,说明找到了匹配的字符串,我们将计数器count加1,并将index更新为匹配字符串的下一个索引位置。最终,返回计数器的值作为结果。
请注意,上述代码只能计算目标字符串在待查询字符串中的非重叠出现次数。如果需要计算重叠出现次数,可以将index的更新改为index++
。