how to check the word is present in given char array in c

Solutions on MaxInterview for how to check the word is present in given char array in c by the best coders in the world

showing results for - "how to check the word is present in given char array in c"
Malak
21 Jul 2019
1#include <stdio.h>
2int main()
3{
4    char c_to_search[5] = "asdf";
5
6    char text[68] = "hello my name is \0 there is some other string behind it \n\0 asdf";
7
8    int pos_search = 0;
9    int pos_text = 0;
10    int len_search = 4;
11    int len_text = 67;
12    for (pos_text = 0; pos_text < len_text - len_search;++pos_text)
13    {
14        if(text[pos_text] == c_to_search[pos_search])
15        {
16            ++pos_search;
17            if(pos_search == len_search)
18            {
19                // match
20                printf("match from %d to %d\n",pos_text-len_search,pos_text);
21                return;
22            }
23        }
24        else
25        {
26           pos_text -=pos_search;
27           pos_search = 0;
28        }
29    }
30    // no match
31    printf("no match\n");
32   return 0;
33}
34