Created
September 15, 2017 18:04
-
-
Save prmichaelsen/9e4b2b64a24242f5f0d32be2b6f71cb6 to your computer and use it in GitHub Desktop.
with only stdio, count number of occurrences of a substring within a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int countSubstr(char string[], char substring[]) | |
{ | |
int count = 0; | |
size_t i = -1; | |
while(string[++i]) | |
{ | |
int match = 1; | |
size_t j = 0; | |
while (substring[j]) | |
{ | |
match &= substring[j] == string[i + j++]; | |
} | |
count += match; | |
} | |
return count; | |
} | |
void test(char name[], int expected, char string[], char substring[]){ | |
int actual = countSubstr(string, substring); | |
char* status = (actual == expected)? "PASS" : "FAIL"; | |
printf("%s: %s\nActual: %d\nExpected: %d\n\n",name,status,actual,expected); | |
} | |
int main(void) { | |
test("Two empty strings", 0, "", ""); | |
test("Empty substring", 19, "sub str sub str sub", ""); | |
test("Empty string", 0, "", "sub"); | |
test("Case 1", 4, "dbdbsnasdb dbdxx", "db"); | |
test("Case 2", 3, "dbdbsnasmfdb", "db"); | |
test("No match", 0, "dbdbsnasmfdb", "dxb"); | |
test("Inner matching", 3, "abababa", "aba"); | |
test("Identity test", 1, "a", "a"); | |
test("Longer substring", 0, "a", "abcd"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment