在毕老师第13天讲的String课程中,他举到这样一个例子:
获取一个字符中在另一个字符串中出现的次数,他是这样写的:
class StringTest
{
public static int getSubCount(String str,String key)
{
int count = 0;
int index = 0;
while((index=str.indexOf(key))!=-1)
{
System.out.println("str=:"+str);
str = str.substring(index+key.length());
count++;
}
return count;
}
public static void main(String[] args)
{
String str = "abkkcdkkefkkskk";
System.out.println("count="+getSubCount(str,"kk"));
}
}
当str = "kkkkk", key="kk"的时候,毕老师的程序运行结果是count = 2;
我觉得应该这样:
class StringTest
{
public static int getSubCount(String str,String key)
{
int count = 0;
int index = 0;
while((index=str.indexOf(key))!=-1)
{
System.out.println("str=:"+str);
str = str.substring(index+1);
count++;
}
return count;
}
public static void main(String[] args)
{
String str = "kkkkk";
System.out.println("count="+getSubCount(str,"kk"));
}
}
i这样str = "kkkkk",key = "kk"运行结果count = 4;
|
|