- 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;
- }
- }
复制代码
|
|