记录一个字符串出现的次数

首先定义一个计时器count= 0,然后判断父字符串中是否有子字符串,如果没有则直接返回count= 0,如果判断有,则定义一个变量index = 0  记录子字符串key出现的位置,然后生成一个新的字符串对象 str 利用substring()方法将其从index(index=0)+key.length位置截取生成一个新的字符串接着遍历,同时count++记录出现的次数。

package cn.lyun.zzj;

public class Test06 {
    public static void main(String[] args) {
    String str = "nba ernsdfbfa tnba ynba ui";
    String key = "nba";
    int count = getKeyStringCount( str, key);
    System.out.println("count = " +count);
}

    private static int getKeyStringCount(String str, String key) {
        int count = 0;
        if (!str.contains(key)) {
            return count;
        }
        int index = 0;
        while((index = str.indexOf(key))!=-1){
            str = str.substring(index+key.length());
            count ++;
        }
        return count;
    }
}

猜你喜欢

转载自www.cnblogs.com/ivan999/p/10568885.html