-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
  • 100,966
  • 191
  • 140
  • 197

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
  • 76,500
  • 11
  • 62
  • 80