思想一:
1.声明次数count=0;
* 2.计算子串的长度。
* 3.按照子串的长度,从整串的开始位置开始搜索,判断子串长度个字符,看是否与子串相同,
* 若相同,count+1.
* 4.搜索位置+1;知道搜索位置等于整串.length-子串.length结束搜索。
* 5.输出count。
*/
public class StringTest {
/**
* @param args
*/
public static int computeCount(String str, String substr)
{
int count=0;
for(int i=0;i<=str.length()-substr.length();i++)
{
String str2=str.substring(i,i+substr.length());
if(str2.contains(substr))
count++;
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="nbaernbanbatynbauinbaopnba";
String substr="nba";
int count=computeCount(str,substr);
System.out.println(substr+"在"+str+"中出现了"+count+"次");
}
}
思想二:
1.定义出现次数count=0;
* 2.确定整串的搜索位置,从index=0开始,通过indexOf获取子串第一次出现的位置index,count+1。
* 3.接下来搜索位置index=index+子串.长度。
* 4.搜索直到indexOf()返回-1.搜索结束。
public class StringTest2 {
public static int computeCount(String str, String key)
{
int count=0;
int index=0;
while((index=str.indexOf(key,index))!=-1)
{
count++;
index=index+key.length();
}
return count;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="nbaernbanbatynbauinbaopnba";
String substr="nba";
int count=computeCount(str,substr);
System.out.println(substr+"在"+str+"中出现了"+count+"次");
}
}