黑马程序员技术交流社区
标题:
统计一个字符串在某个字符串中出现的次数
[打印本页]
作者:
肚小糖
时间:
2015-8-25 15:48
标题:
统计一个字符串在某个字符串中出现的次数
public class StringTest{
public static void main(String[] args){
String str = "nbaernbatynbauinbaopnba";
String key = "nba";
int count = getKeyStringCount(str, key);
System.out.println("count = "+count);
}
public static int getKeyStringCount(String str, String key){
int count = 0;
int index = 0;
//用indexOf获取字串在字符串中出现的位置,如果找不到返回-1,跳出while循环
while((index = str.indexOf(key))!=-1){
//每找到一个字串,就把剩余字符串(substring(出现位置+子串的长度))赋给str变量,继续查找str。
str = str.substring(index + key.length());
count ++ ;
}
return count;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2