Demo17_API_String2

package test08;

public class Demo17_API_String2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String str = "sdsdfdgrsdwvrtysd" ;
        String key = "d" ; 
        /*int x =str.indexOf(key,0);//从开始位查找
        System.out.println("x="+x);
        int y =str.indexOf(key, x+key.length());//从指定位查找,循环多次
        System.out.println("y="+y);*/

        int count  = getKeyCount(str,key);
        System.out.println("count= "+count);
    }

    public static int getKeyCount(String str, String key) {
//      定义变量,记住每一次找到的key的位置
        int index = 0 ;
//      定义变量,记录出现的次数
        int count = 0 ;
//      定义循环 , 只要检索到的位置不是一,继续查找
        while((index = str.indexOf(key,index))!= -1)
        {
//          每循环一次,就要明确下一次查找的位置
            index = index + key.length();
//          每查找一次,count自增
            count++;
        }


        return count;
    }

}

猜你喜欢

转载自blog.csdn.net/mingxu_W/article/details/81871623