How to find string in other string, return the index of the string in found or -1 if not, in C

1 Answer

0 votes
#include <stdio.h>
  
#define LEN 50

int find_in_str_s(char s[], char to_find[]);
  
int main(void)
{
    char s[LEN] = "Welcome to the home of wisdom";
  
    printf("%d\n", find_in_str_s(s, "home"));
    printf("%s\n", &s[find_in_str_s(s, "home")]);
    printf("%d\n", find_in_str_s(s, "geek"));
    
    return 0;
}

int find_in_str_s(char s[], char to_find[]) 
{ 
    int i, j, k; 
    
    for (i = 0; s[i] != '\0'; i++) 
    { 
           for (j = i, k = 0; to_find[k] != '\0' && s[j] == to_find[k]; j++, k++);
           
           if (k > 0 && to_find[k] == '\0') 
               return i; 
    } 
       
    return -1; 
} 
 
 
/*
run:
    
15
home of wisdom
-1
 
*/

 



answered Nov 16, 2015 by avibootz
...