I am trying to write a function that will count the occurrences of a pattern in a string without overlap. This is what I have right now.
size_t count(char *string, char *pat) {
size_t patternLength = strlen(pat);
size_t stringLength = strlen(string);
size_t count = 0;
char *compareString = malloc(patternLength + 1);
for (int i = 0; i < stringLength; i++) {
if (i + patternLength > stringLength) return count;
strcpy(compareString, &string[i], i+patternLength);
if (strcmp(compareString, pat) == 0) {
count++;
i--;
i+=patternLength; /* non overlapping find */
}
}
free(compareString);
return count;
}