0

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;
  }
}
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
Arrow
  • 3
  • 2

3 Answers3

1

Try using this

import java.util.regex.Pattern;
import java.util.regex.Matcher;

 public static int countOccurence2(String[]arr, String n) {
    Pattern p = Pattern.compile(n.toLowerCase());
    int count = 0;
    for(int i = 0; i < arr.length; i++)
    {
        Matcher m = p.matcher(arr[i].toLowerCase());
        while (m.find()) {
            count++;
        }
    }
    return count;
 }

What it does is that it uses regular expression to match a pattern in the given string. And I think toLowerCasse() is a self-explanatory method, no need to give an explanation for it.

If you want it to be case-sensitive, just remove the toLowerCase().

omar jayed
  • 850
  • 5
  • 16
1

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

RaffleBuffle
  • 5,396
  • 1
  • 9
  • 16
0

You can have a look at: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#countMatches(java.lang.String,%20java.lang.String)

  /**
   * <p>Counts how many times the substring appears in the larger string.</p>
   *
   * <p>A {@code null} or empty ("") String input returns {@code 0}.</p>
   *
   * <pre>
   * StringUtils.countMatches(null, *)       = 0
   * StringUtils.countMatches("", *)         = 0
   * StringUtils.countMatches("abba", null)  = 0
   * StringUtils.countMatches("abba", "")    = 0
   * StringUtils.countMatches("abba", "a")   = 2
   * StringUtils.countMatches("abba", "ab")  = 1
   * StringUtils.countMatches("abba", "xxx") = 0
   * </pre>
   *
   * @param str  the CharSequence to check, may be null
   * @param sub  the substring to count, may be null
   * @return the number of occurrences, 0 if either CharSequence is {@code null}
   * @since 3.0 Changed signature from countMatches(String, String) to countMatches(CharSequence, CharSequence)
   */
  public static int countMatches(final CharSequence str, final CharSequence sub) {
      if (isEmpty(str) || isEmpty(sub)) {
          return 0;
      }
      int count = 0;
      int idx = 0;
      while ((idx = CharSequenceUtils.indexOf(str, sub, idx)) != INDEX_NOT_FOUND) {
          count++;
          idx += sub.length();
      }
      return count;
  }

  /**
   * Used by the indexOf(CharSequence methods) as a green implementation of indexOf.
   *
   * @param cs the {@code CharSequence} to be processed
   * @param searchChar the {@code CharSequence} to be searched for
   * @param start the start index
   * @return the index where the search sequence was found
   */
  static int indexOf(final CharSequence cs, final CharSequence searchChar, final int start) {
      return cs.toString().indexOf(searchChar.toString(), start);
  }
geffchang
  • 3,279
  • 2
  • 32
  • 58
  • I am trying to find only the lower case cat's so n is set to "cat" I don't need Cat. So the Error is at "Ilovecatcat" I get the first "cat" but not the second "cat", and I don't know how to use indexOf to get it since It only gets the first occurrence. Output: 3, 1, 0 when returning count; Answer: 4, 1, 0 – Arrow Apr 02 '20 at 03:39
  • @Arrow Updated answer – geffchang Apr 02 '20 at 04:00