fork download
  1. // gcc -std=c99
  2. #include <stdbool.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5.  
  6. static int
  7. count_substr(const char *str, const char* substr, bool overlap) {
  8. if (strlen(substr) == 0) return -1;
  9.  
  10. int count = 0;
  11. int increment = overlap ? 1 : strlen(substr);
  12. for (char* s = (char*)str; (s = strstr(s, substr)); s += increment)
  13. ++count;
  14. return count;
  15. }
  16.  
  17. int main() {
  18. char *substrs[] = {"a", "aa", "aaa", "b", "", NULL };
  19.  
  20. for (char** s = substrs; *s != NULL; ++s)
  21. printf("'%s' -> %d, no overlap: %d\n", *s, count_substr("aaaaa", *s, true),
  22. count_substr("aaaaa", *s, false));
  23. }
  24.  
Success #stdin #stdout 0.02s 1720KB
stdin
Standard input is empty
stdout
'a' ->  5, no overlap: 5
'aa' ->  4, no overlap: 2
'aaa' ->  3, no overlap: 1
'b' ->  0, no overlap: 0
'' ->  -1, no overlap: -1