java實現在一個字元串中查找某個子字元串出現的次數

  public static void main(String[] args) {
        String a = "我愛我的祖國!!!";
        String b = "愛";

        System.out.println(strCount(a, b));

    }

    /**
     *
     * @param str 源字元串
     * @param findByStr 被查詢的字元串
     * @return 返回findByStr在str中出現的次數
     */
    public static int strCount(String str,String findByStr){
        String[] split = str.split("");
        return Arrays.asList(split).stream().filter(s -> s.equals(findByStr)).collect(Collectors.toList()).size();
    }

 

Tags: