记算出一个字符串在另一个字符串中出现的次数

来源:互联网 发布:linux的两大就业方向 编辑:程序博客网 时间:2024/05/17 09:08
/*
 * 算法:
 * 总长度-去掉字符串后剩余长度 = 被去掉的字符串长度 
 * 被去掉的字符串长度 / 去掉的字符串 = 个数
 * 
 * 比如总长度为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);
}
}


转自老紫竹:http://blog.csdn.net/java2000_net/archive/2008/09/09/2905804.aspx