• Register
+2 votes


I just started learning java and solving problems from various online websites. Stuck on a problem saying, count how many times a substring appears in a string java.

This problem is beyond my understanding. I found Kodlogs very helpful and friendly environment platform to ask a question. If anybody could reply to my thread and give me a possible solution (with code snippet) would be great for me, and I must recognize your help.
Thanks in advance, mate.

ago by (6k points)  

1 Answer

+1 vote


Hello Gavin,

You’ve asked an interesting question. This is a string data type question regarding java. In the program, our quest is to find out substrings in a string. Let’s try to solve the problem through a simple code below:

public class SubStringCount {
  public static int countTarget(String st, String subst) {
      if (isEmpty(st) || isEmpty(subst)) {
          return 0;
      int counter = 0;
      int index = 0;
      while ((index = st.indexOf(subst, index)) != -1) {
          index += subst.length();
      return counter;

  public static boolean isEmpty(String st) {
      return st == null || st.length() == 0;

If you’ve got any question please reply to this thread. Thanks

ago by (17.9k points)