1
0
forked from 131/lab3_test
Files
lab3_test/str_lib.c

56 lines
1.3 KiB
C
Raw Normal View History

#include <stddef.h>
2023-03-25 03:58:02 +03:00
/**
* mystrlen - Вычисляет длину строки.
* @str: Указатель на строку.
*
* Возвращает: Длину строки.
2023-03-25 03:58:02 +03:00
*/
size_t mystrlen(const char *str) {
size_t len = 0;
if (str == NULL) {
return 0;
}
while (str[len] != '\0') {
len++;
}
return len;
2023-03-25 03:58:02 +03:00
}
/**
* mystr_idx - Находит первое вхождение подстроки.
* @haystack: Строка, в которой ищется подстрока.
* @needle: Подстрока, которую нужно найти.
*
* Возвращает: Индекс первого вхождения, или -1, если не найдено.
2023-03-25 03:58:02 +03:00
*/
int mystr_idx(const char *haystack, const char *needle) {
if (haystack == NULL || needle == NULL) {
return -1;
}
if (*needle == '\0') {
return 0;
}
size_t h_len = mystrlen(haystack);
size_t n_len = mystrlen(needle);
2023-03-25 03:58:02 +03:00
if (n_len > h_len) {
return -1;
}
for (size_t i = 0; i <= h_len - n_len; i++) {
int found = 1;
for (size_t j = 0; j < n_len; j++) {
if (haystack[i + j] != needle[j]) {
found = 0;
break;
}
}
if (found) {
return i;
}
}
return -1;
}