class StringTest
{
//方式一
public static int getSubCount(String str,String key)
{
int count = 0;
int index = 0;
while((index = str.indexof(key)) != -1)
{
str = str.substring(index+key.length());
count++;
}
return count;
}
//方式二
public static int getSubCount_2(String str,String key)
{
int count = 0;
int index = 0;
while((index = str.indexof(key,index)) !=-1)
{
sop("index="+index);
index= index + key.length();
count++;
}
return count;
}
public static void main(String [] args)
{
String str = "abkkcdkkefkkskk";
sop("count="+getSubCount(str,"kk"));
}
public static void sop(String str)
{
System.out.println(str);
}
}
查找字符串中子串出现的次数
最新推荐文章于 2024-05-03 08:43:15 发布