package cn.itcast.string.demo;
public class StringTest2 {
public static void main(String[] args) {
/*
* 2.一个子串在整串中出现的次数。
* "nbaernbatynbauinbaophba"
*/
/**
*
*/
String str = "nbaernbatynba";
String key = "nba";
int count = getKeyStringCount(str,key);
System.out.println("count="+count);
/**
* 获取子串在整串中出现的次数。
* @author WangYu
* @param str
* @param key
*/
}
public static int getKeyStringCount(String str, String key)
{
//1.定义计数器
int count = 0;
//2.定义变量记录key出现的位置
int index = 0;
while((index = str.indexOf(key,index))!=-1)
{
//str = str.substring(index+key.length());
index = index+key.length();
count++;
}
return count;
}
}
15-10-常用对象API(String类-练习2-子串的次数)
最新推荐文章于 2020-12-16 17:37:09 发布