Files
lab1_git/stridx.c
2025-10-11 07:22:07 -04:00

55 lines
1.8 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
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;
}