Arrow
Arrow

Reputation: 3

Counting the Occurrence of a String in an Array of Strings

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;
  }
}

Upvotes: 0

Views: 1345

Answers (3)

RaffleBuffle
RaffleBuffle

Reputation: 5455

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

Upvotes: 1

geffchang
geffchang

Reputation: 3340

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);
  }

Upvotes: 0

omar jayed
omar jayed

Reputation: 868

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().

Upvotes: 1

Related Questions