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;
  }
}
3
  • Is it what u want? stackoverflow.com/questions/8098601/… Commented Apr 2, 2020 at 3:35
  • 1
    What output do you get when you run your program? What output do you expect instead? Commented Apr 2, 2020 at 3:37
  • Output I get: 3, 1, 0 Output I need 4, 1, 0 Commented Apr 2, 2020 at 3:40

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

2 Comments

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 Updated answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.