stridx
This commit is contained in:
54
stridx.c
Normal file
54
stridx.c
Normal file
@@ -0,0 +1,54 @@
|
||||
#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;
|
||||
}
|
||||
Reference in New Issue
Block a user