Write strstr
Completed
Write int find(char *text, char *word) that returns the index of the first occurrence of word in text, or -1, using nested loops. Read a line and a word and print the index.
Input
Line 1: text. Line 2: word.
Output
An index.
Example
Input
the cat sat on the mat sat
Output
8
Editor
C
Hints
Try every starting position; compare character by character.
Solution explanation
This brute-force search is O(n·m); real libraries use smarter algorithms for long texts.
Show solution
#include <stdio.h>
#include <string.h>
int find(char *text, char *word) {
int n = strlen(text), m = strlen(word);
for (int i = 0; i + m <= n; i++) {
int j = 0;
while (j < m && text[i + j] == word[j]) j++;
if (j == m) return i;
}
return -1;
}
int main() {
char text[200], word[50];
fgets(text, 200, stdin);
text[strcspn(text, "\n")] = '\0';
scanf("%s", word);
printf("%d\n", find(text, word));
return 0;
}