API库的String用法

package test;

public class Count {
    public static void main(String[] args){
        String str="宝钗是何等老谋深算,宝玉、黛玉说话想讨便宜哪里是宝钗的对手,凤姐虽不通达,但只见他三人行影,便知其意,这是王熙凤的强项、黛玉说话着急了,把宝玉逼到墙角";
        String key1="黛玉";
        String key2="宝玉";
        String key3="宝钗";
        int count1=getKeyCount(str,key1);
        System.out.println("黛玉出现的次数为:"+count1);
        int count2=getKeyCount(str,key2);
        System.out.println("宝玉出现的次数为:"+count2);
        int count3=getKeyCount(str,key3);
        System.out.println("宝钗出现的次数为:"+count3);
    }

    public static int getKeyCount(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+2);
            //str=str.substring(index+key.length());
            count++;
        }

        return count;
    }


}

计算个数

你可能感兴趣的:(java,开发语言)