Occurrences of substring in a string

后端 未结 24 1855
眼角桃花
眼角桃花 2020-11-22 03:35

Why is the following algorithm not halting for me? (str is the string I am searching in, findStr is the string I am trying to find)

String str = \"helloslkhe         


        
24条回答
  •  醉话见心
    2020-11-22 03:56

    Do you really have to handle the matching yourself ? Especially if all you need is the number of occurences, regular expressions are tidier :

    String str = "helloslkhellodjladfjhello";
    Pattern p = Pattern.compile("hello");
    Matcher m = p.matcher(str);
    int count = 0;
    while (m.find()){
        count +=1;
    }
    System.out.println(count);     
    

提交回复
热议问题