From 21777685cabc5f68649c762d7fad9b17b7eb4f81 Mon Sep 17 00:00:00 2001 From: Lil_Big_Shib Date: Sat, 11 Oct 2025 07:22:07 -0400 Subject: [PATCH] stridx --- stridx.c | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 stridx.c diff --git a/stridx.c b/stridx.c new file mode 100644 index 0000000..1ff38c8 --- /dev/null +++ b/stridx.c @@ -0,0 +1,54 @@ +#include + +int mystr_idx(char *str, char *substr) { + // Если подстрока пустая, возвращаем 0 + if (substr == NULL || *substr == '\0') { + return 0; + } + + // Если строка пустая, возвращаем -1 + if (str == NULL || *str == '\0') { + return -1; + } + + int i = 0; + while (str[i] != '\0') { + int j = 0; + // Проверяем, совпадает ли подстрока начиная с позиции i + while (substr[j] != '\0' && str[i + j] != '\0' && str[i + j] == substr[j]) { + j++; + } + + // Если дошли до конца подстроки, значит нашли полное совпадение + if (substr[j] == '\0') { + return i; + } + + i++; + } + + return -1; +} + +// Функция для тестирования +void test_mystr_idx() { + printf("mystr_idx(\"helloworld\", \"world\") = %d (expected: 5)\n", + mystr_idx("helloworld", "world")); + printf("mystr_idx(\"helloworld\", \"helloworld\") = %d (expected: 0)\n", + mystr_idx("helloworld", "helloworld")); + printf("mystr_idx(\"helloworld\", \"foo\") = %d (expected: -1)\n", + mystr_idx("helloworld", "foo")); + printf("mystr_idx(\"helloworld\", \"hello\") = %d (expected: 0)\n", + mystr_idx("helloworld", "hello")); + printf("mystr_idx(\"helloworld\", \"low\") = %d (expected: 3)\n", + mystr_idx("helloworld", "low")); + printf("mystr_idx(\"\", \"test\") = %d (expected: -1)\n", + mystr_idx("", "test")); + printf("mystr_idx(\"test\", \"\") = %d (expected: 0)\n", + mystr_idx("test", "")); +} + +int main() { + test_mystr_idx(); + return 0; +}