Count the occurrences of a letter in a string

前端 未结 10 1659
礼貌的吻别
礼貌的吻别 2021-01-21 03:42

I am trying to write a for loop in Java that will count the occurrences of a letter in a string. The user will enter the letter to count and the string in which to search. This

10条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-21 04:10

    No need to loop:

        String sentence = "abcabcabcd";
        String letter = "b";
        int numOfOccurences = sentence.length() - 
                              sentence.replaceAll(letter, "").length();
        System.out.println("numOfOccurences = "+numOfOccurences);
    

    OUTPUT:

    numOfOccurences = 3
    

提交回复
热议问题