Skip to content

Instantly share code, notes, and snippets.

@itissid
Last active July 25, 2017 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itissid/c6b2dd2f3ffd55874dc8c2a721716a08 to your computer and use it in GitHub Desktop.
Save itissid/c6b2dd2f3ffd55874dc8c2a721716a08 to your computer and use it in GitHub Desktop.
public class CountMatches{
public static void main(String []args){
int c = CountMatches.countMatches("abcabdabdab", "abdab");
System.out.println(String.format("Count: %d", c ));
}
public static int countMatches(String str, String sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = str.indexOf(sub, idx)) != -1) {
count++;
idx += sub.length();
}
return count;
}
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment