/**
* 计算字符串中子串出现的次数
* Created with IntelliJ IDEA.
* User: jackzhao
* Date: 14-1-22
* Time: 下午8:08
* To change this template use File | Settings | File Templates.
*/
public class TestFindString {
public static void main(String[] arg){
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入字符串:");
try{
String str1=br.readLine();
System.out.println("======================");
System.out.println("请输入需要查找的字串:");
String str2=br.readLine();
int number=findStringNumber(str1,str2);
System.out.println("字串在此字符串中出现的次数为:"+number);
}
catch (Exception ex)
{}
}
/**
*
* @param str1 字符串
* @param str2 需要查找的字串
* @return 返回字串的个数
*/
private static int findStringNumber(String str1, String str2)
{
int count=0;
char[] chars1=str1.toCharArray();
char[] chars2=str2.toCharArray();
for(int i=0,j=0;i<chars1.length;i++)
{
for(j=0;j<chars2.length;j++)
{
if(chars1[i+j]!=chars2[j])
break;
}
if(j==chars2.length)
{
count++;
i=i+j-1;
}
}
return count;
}
}