/*
3.获取一个字符串的在另一个字符串中出现的次数。
"abkkcdkkefkkskk"
思路:
1.定义计数器。
2.获取kk第一次出现的位置。
3.从第一次出现位置后剩余的字符串中级车获取kk出现的位置。
每获取一次就计数一次。
4.当获取不到时,计数完成。
*/
class StringTes2
{
public static void main(String args[])
{
String str = "abkkcdkkefkkskk";
sop("count="+getSubCount_2(str,"kk"));
}
//练习三:方法1:从子串找
public static int getSubCount(String str,String key)
{
//定义计数器。
int count=0;
//位置也是变化的,定义一个变量记录索引计数的位置
int index=0;
while((index=str.indexOf(key))!=-1)
{
sop("str="+str);
//子串是变化的,位置+ker的长度
str = str.substring(index+key.length());
count++;
}
return count;
}
//练习三:方法2:从第一个找
public static int getSubCount_2(String str,String key)
{
//定义计数器。
int count=0;
//位置也是变化的,定义一个变量记录索引计数的位置
int index=0;
while((index=str.indexOf(key,index))!=-1)
{
sop("str="+index);
//sop("count="+split("kk").length);//不建议使用,前面有kk就不行
index=index+key.length();
count++;
}
return count;
}
public static void sop(String str)
{
System.out.println(str);
}
}
网友评论