/*
* 算法:
* 总长度-去掉字符串后剩余长度 = 被去掉的字符串长度
* 被去掉的字符串长度 / 去掉的字符串 = 个数
*
* 比如总长度为100, 查找的为10, 则去掉所有的查找的字符串后,长度为80
* 则100-80 = 被去掉的字符串 = 20
* 20/10 = 被去掉了2个,所以里面也就包含了2个。
*/
public class CalStringTimes {
/**
* 记算出一个字符串在另一个字符串中出现的次数
* @param yangjianguo
*/
public static int calString(String str1, String str2) {
int count = (str1.length() - str1.replace(str2, "").length())
/ str2.length();
return count;
}
public static void main(String[] args) {
String str1 = "Request Request Request Request Request Request ";
String str2 = "Request Request ";
int num = calString(str1,str2);
System.out.println(num);
}
}
本文介绍了一种通过计算字符串替换前后的长度差来确定子字符串出现次数的方法,并提供了一个具体的Java实现示例。

1158

被折叠的 条评论
为什么被折叠?



