Counting the Occurrence of a String in an Array of Strings

Arrow :

I figured out how to count the occurrence of all the strings expect one of them because I am using indexOf because I haven't learned anything new in this class that I'm taking so I was wondering if I can get help here is the code. (Not able to count the Bolded "cat")

class Main {


  public static void main(String[] args) {
    String[] arr= {"Catcat", "Dogsaregoodcatsarebetter", "Ilovecatcat", "Goatsarecutetoo"};
    System.out.println(countOccurence2(arr, "cat"));
    System.out.println(countOccurence2(arr, "cute"));
    System.out.println(countOccurence2(arr, "horse"));

  }


  public static int countOccurence2(String[]arr, String n)

  {

        int count = 0;


        for(int i = 0; i < arr.length; i++)
        {
            if(arr[i].indexOf(n) != -1)
            {

               count++;


            }
        }
        return count;
  }
}
SirRaffleBuffle :

You can use indexOf to count all occurrences of a string, but you have to use the form that takes the index at which to start counting, which will be the previously found index plus the length of the query string.

public static int countOccurence2(String[]arr, String n)
{
    int count = 0;
    for(int i = 0; i < arr.length; i++)
    {
      int idx = arr[i].indexOf(n);
      while(idx != -1)
      {
        count++;
        idx = arr[i].indexOf(n, idx+n.length());
      }
    }
    return count;
}

Which produces the desired output: 4,1,0

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=393499&siteId=1