forked from 131/lab3_test
Implement mystrlen and mystr_idx functions
This commit is contained in:
33
munit/str_lib.c
Normal file
33
munit/str_lib.c
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
#include "str_lib.h"
|
||||||
|
|
||||||
|
size_t mystrlen(const char *str) {
|
||||||
|
if (!str) return 0;
|
||||||
|
size_t len = 0;
|
||||||
|
while (str[len] != '\0') {
|
||||||
|
len++;
|
||||||
|
}
|
||||||
|
return len;
|
||||||
|
}
|
||||||
|
|
||||||
|
int mystr_idx(const char *str, const char *substr) {
|
||||||
|
if (!str || !substr) return -1;
|
||||||
|
|
||||||
|
size_t str_len = mystrlen(str);
|
||||||
|
size_t substr_len = mystrlen(substr);
|
||||||
|
|
||||||
|
if (substr_len == 0) return 0;
|
||||||
|
if (substr_len > str_len) return -1;
|
||||||
|
|
||||||
|
for (size_t i = 0; i <= str_len - substr_len; i++) {
|
||||||
|
int found = 1;
|
||||||
|
for (size_t j = 0; j < substr_len; j++) {
|
||||||
|
if (str[i + j] != substr[j]) {
|
||||||
|
found = 0;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (found) return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user