Directory: | ./ |
---|---|
File: | s21_strstr.c |
Date: | 2025-07-13 17:59:14 |
Exec | Total | Coverage | |
---|---|---|---|
Lines: | 38 | 38 | 100.0% |
Branches: | 22 | 22 | 100.0% |
Line | Branch | Exec | Source |
---|---|---|---|
1 | #include "s21_string.h" | ||
2 | |||
3 | s21_size_t* getPi(const char* needle, s21_size_t lengthNeedle); | ||
4 | |||
5 | 7 | char* s21_strstr(const char* haystack, const char* needle) { | |
6 | 7 | s21_size_t lengthHaystack = s21_strlen(haystack); | |
7 | 7 | s21_size_t lengthNeedle = s21_strlen(needle); | |
8 | |||
9 | 7 | s21_size_t* pi = S21_NULL; | |
10 |
2/2✓ Branch 0 taken 5 times.
✓ Branch 1 taken 2 times.
|
7 | if (lengthNeedle > 0) { |
11 | 5 | pi = getPi(needle, lengthNeedle); | |
12 | } | ||
13 | |||
14 | 7 | s21_size_t i = 0; | |
15 | 7 | s21_size_t j = 0; | |
16 |
4/4✓ Branch 0 taken 97 times.
✓ Branch 1 taken 6 times.
✓ Branch 2 taken 96 times.
✓ Branch 3 taken 1 times.
|
103 | while (i < lengthHaystack && j < lengthNeedle) { |
17 |
2/2✓ Branch 0 taken 72 times.
✓ Branch 1 taken 24 times.
|
96 | if (needle[j] == haystack[i]) { |
18 | 72 | i++; | |
19 | 72 | j++; | |
20 |
2/2✓ Branch 0 taken 4 times.
✓ Branch 1 taken 20 times.
|
24 | } else if (j == 0) { |
21 | 4 | i++; | |
22 | } else { | ||
23 | 20 | j = pi[j - 1]; | |
24 | } | ||
25 | } | ||
26 | |||
27 | 7 | char* result = S21_NULL; | |
28 |
2/2✓ Branch 0 taken 2 times.
✓ Branch 1 taken 5 times.
|
7 | if (lengthNeedle == 0) { |
29 | 2 | result = (char*)haystack; | |
30 |
2/2✓ Branch 0 taken 3 times.
✓ Branch 1 taken 2 times.
|
5 | } else if (j == lengthNeedle) { |
31 | 3 | result = (char*)(haystack + i - lengthNeedle); | |
32 | } | ||
33 | |||
34 |
2/2✓ Branch 0 taken 5 times.
✓ Branch 1 taken 2 times.
|
7 | if (pi != S21_NULL) { |
35 | 5 | free(pi); | |
36 | } | ||
37 | 7 | return result; | |
38 | } | ||
39 | |||
40 | 5 | s21_size_t* getPi(const char* needle, s21_size_t lengthNeedle) { | |
41 | 5 | s21_size_t* pi = malloc(lengthNeedle * sizeof(s21_size_t)); | |
42 | |||
43 | 5 | pi[0] = 0; | |
44 | 5 | s21_size_t j = 0; | |
45 | 5 | s21_size_t i = 1; | |
46 | |||
47 |
2/2✓ Branch 0 taken 38 times.
✓ Branch 1 taken 5 times.
|
43 | while (i < lengthNeedle) { |
48 |
2/2✓ Branch 0 taken 22 times.
✓ Branch 1 taken 16 times.
|
38 | if (needle[j] == needle[i]) { |
49 | 22 | pi[i] = j + 1; | |
50 | 22 | j++; | |
51 | 22 | i++; | |
52 |
2/2✓ Branch 0 taken 11 times.
✓ Branch 1 taken 5 times.
|
16 | } else if (j == 0) { |
53 | 11 | pi[i] = 0; | |
54 | 11 | i++; | |
55 | } else { | ||
56 | 5 | j = pi[j - 1]; | |
57 | } | ||
58 | } | ||
59 | |||
60 | 5 | return pi; | |
61 | } | ||
62 |