diff --git a/cstring.h b/cstring.h index f99bd4c..2f6790d 100644 --- a/cstring.h +++ b/cstring.h @@ -941,4 +941,23 @@ double stringToDouble(TString s) { return number + decimal; } +size_t stringCountSubstring(TString s, TString pattern) { + size_t count = 0; + TString tmp = stringInitWithCharArr(s.data); + size_t pattern_length = pattern.size; + size_t shift = 0; + + if (pattern_length == 0) { + return 0; + } + + while (stringContains(tmp, pattern)) { + shift = stringFindFirst(tmp, pattern) + pattern_length; + count++; + tmp.data += shift; + tmp.size -= shift; + } + return count; +} + #endif diff --git a/tests/main.c b/tests/main.c index 92621be..22a2c41 100644 --- a/tests/main.c +++ b/tests/main.c @@ -483,6 +483,18 @@ void test_stringToDouble() { printGreen("stringToDouble\n"); } +void test_stringCountSubstring() { + TString s1 = stringInitWithCharArr("abc1234dgdgdsfsfdfdsfsfsd1234sfdjg"); + TString s2 = stringInitWithCharArr("123"); + + size_t result = 2; + assertEq(stringCountSubstring(s1, s2), result); + stringDestroy(&s1); + stringDestroy(&s2); + + printGreen("stringCountSubstring\n"); +} + int main() { test_stringStartWith(); test_stringEndWith(); @@ -511,5 +523,6 @@ int main() { test_stringIsPalindrome(); test_stringPad(); test_stringRemove(); + test_stringCountSubstring(); return 0; }