'How to count the amount of substring occurences? [duplicate]
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.
Solution 1:[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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
