Complete the code to find the first occurrence of a substring in a string using strstr.
char *result = strstr(text, [1]);The strstr function searches for the first occurrence of the substring pattern in text.
Complete the code to compare two characters in the text and pattern during substring search.
if (text[i] == [1][j]) {
We compare the character at position i in text with the character at position j in pattern to check for a match.
Fix the error in the loop condition to avoid reading beyond the text length during substring search.
for (int i = 0; i <= text_length - [1]; i++) {
The loop should run until i reaches text_length - pattern_length to avoid going past the end of the text when checking for the pattern.
Fill both blanks to correctly check if the substring matches the text segment.
if (j == [1]) { return [2]; }
When j equals pattern_length, it means the whole pattern matched, so we return the starting index i of the match in the text.
Fill all three blanks to complete the naive substring search function.
int naive_search(char *text, char *pattern) {
int text_len = strlen(text);
int pattern_len = strlen(pattern);
for (int i = 0; i <= text_len - [1]; i++) {
int j = 0;
while (j < [2] && text[i + j] == pattern[[3]]) {
j++;
}
if (j == pattern_len) {
return i;
}
}
return -1;
}The loop runs until i reaches text_len - pattern_len. The inner while loop checks characters while j is less than pattern_len and characters match. The index j is used to access the pattern characters.
