Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions cstring.h
Original file line number Diff line number Diff line change
Expand Up @@ -941,4 +941,23 @@ double stringToDouble(TString s) {
return number + decimal;
}

size_t stringCountSubstring(TString s, TString pattern) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добавьте заголовок функции в начале файла, где объявляются все импорты

size_t count = 0;
TString tmp = stringInitWithCharArr(s.data);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кажется лучше обойтись без лишнего копирования всей строки, есть функция stringCopy(), которая выполняет не глубокое копирование, а просто получает второй указатель на уже существующую строку. Текущая реализация так вообще содержит утечку памяти((

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
13 changes: 13 additions & 0 deletions tests/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,18 @@ void test_stringToDouble() {
printGreen("stringToDouble\n");
}

void test_stringCountSubstring() {
TString s1 = stringInitWithCharArr("abc1234dgdgdsfsfdfdsfsfsd1234sfdjg");
TString s2 = stringInitWithCharArr("123");
Comment on lines +487 to +488
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добавьте ещё пару тестовых случаев, возможно с вхождениями в начале/конце строки, без вхождений вообще или наоборот только из одинаковых букв.
Например: stringCountSubstring('aaaaa', 'a')


size_t result = 2;
assertEq(stringCountSubstring(s1, s2), result);
stringDestroy(&s1);
stringDestroy(&s2);

printGreen("stringCountSubstring\n");
}

int main() {
test_stringStartWith();
test_stringEndWith();
Expand Down Expand Up @@ -511,5 +523,6 @@ int main() {
test_stringIsPalindrome();
test_stringPad();
test_stringRemove();
test_stringCountSubstring();
return 0;
}