在大串中统计小串出现的次数

来源:互联网 发布:mysql主键和外键 编辑:程序博客网 时间:2024/04/29 10:16
public class Test {    public static void main(String[] args) {       String maxStr="HidingfromtherainandsnowTryingtoforgettobut I won't let go " +               "Looking at a crowded street Listening to my own heart beat";        String minStr="to";        int count = getCount(maxStr, minStr);        System.out.println(count);    }        public static int getCount(String maxStr,String minStr){        //先在大串中查找小串第一次出现的位置        int count=0;        int index = maxStr.indexOf(minStr);        while(index!=-1){            count++;            index=index+minStr.length();            maxStr=maxStr.substring(index);            index=maxStr.indexOf(minStr);        }        return count;    }}
结果:3
0 0