-2

How do I count the amount of times a substring appears in a string? So far I have

static boolean doesAppear(String a, String b){
    boolean appears;
    
    appears = (b.indexOf(a) != -1) ? true : false;
    
    return appears;
}

to confirm that it does appear, but I can't figure out how to adjust it to return true for counts >= 2.

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
  • Welcome. You should take a look at [ask] and take the [tour], if you have not done so already. Also take a look at [example]. – cliff2310 May 14 '22 at 16:19

1 Answers1

1

You can use the fromIndex second argument of String#indexOf to continue looking for the string past the previous occurrence.

public boolean doesAppear(String a, String b, int count){
    int num = 0;
    for(int idx = -1; num < count && (idx = b.indexOf(a, idx + 1)) != -1; num++);
    // You may need to adjust idx + 1 to idx + a.length(), 
    // depending on whether or not you allow overlapping occurrences
    return num >= count;
}
Unmitigated
  • 46,070
  • 7
  • 44
  • 60