In: Computer Science
public static int countSubstrings(java.lang.String t, java.lang.String s, boolean allowOverlap)
Counts the number of times that one string occurs as a substring in another, optionally allowing the occurrences to overlap. For example:
Parameters:
t - string we are looking for ("target")
s - string in which we are looking ("source")
allowOverlap - true if occurrences of t are allowed to overlap
Returns:
number of times t occurs in s as a substring
public class SubStrings {
   public static void main(String[] args) {
      
System.out.println(countSubstrings("aa", "aaaaa", true));
      
System.out.println(countSubstrings("aa", "aaaaa", false));
      
   }
   public static int countSubstrings(java.lang.String t,
java.lang.String s, boolean allowOverlap) {
       int count=0;
       if(allowOverlap) {
           for(int
i=0;i<s.length();i++) {
          
    if(s.substring(i).indexOf(t)!=-1)
          
        count++;
           }
       }
       else {
           int
index=0;
           for(int
i=0;i<s.length();i++) {
          
    if(s.indexOf(t,index)!=-1) {
          
        count++;
          
        index+=t.length();
          
    }
           }
       }
       return count;
   }
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me