1
0
forked from 131/lab3_test
Files
lab3_test/str_lib.c
2025-10-25 05:58:09 -04:00

63 lines
1.5 KiB
C
Raw 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 <string.h>
/*
* Вернуть длину строки.
* Строки в C -- это массив символов, в конце которого находится нулевой символ ( '\0')
*/
int
mystrlen(const char *s)
{
// <YOURCODE>
if (s == NULL) {
return -1; // или 0, в зависимости от требований
}
int length = 0;
while (s[length] != '\0') {
length++;
}
return length;
}
/*
* Найти индекс, с которого строка s2 присутствует в строке s1
* или -1
*/
int
mystr_idx(const char *s1, const char *s2)
{
// <YOURCODE>
if (s1 == NULL || s2 == NULL) {
return -1;
}
int len1 = mystrlen(s1);
int len2 = mystrlen(s2);
// Если подстрока пустая, возвращаем 0
if (len2 == 0) {
return 0;
}
// Если подстрока длиннее строки, она не может содержаться в ней
if (len2 > len1) {
return -1;
}
// Поиск подстроки
for (int i = 0; i <= len1 - len2; i++) {
int j;
for (j = 0; j < len2; j++) {
if (s1[i + j] != s2[j]) {
break;
}
}
// Если дошли до конца подстроки - нашли совпадение
if (j == len2) {
return i;
}
}
return -1;
}