Search sub string - C String

C examples for String:String Function

Description

Search sub string

Demo Code

#include <stdio.h>  
#define MAXLINE 1000 /* maximum input line length */  

int strindex(char source[], char searchfor[]);

char pattern[] = "test";   /* pattern to search for */

                           /* find all lines matching pattern */
int main()/*from   w  ww  .ja va 2 s. com*/
{
   char line[MAXLINE] = "this is a test";

   int index = strindex(line, pattern);
   printf("%s", line);
   printf("%d", index);

   return 0;
}

/* strindex:  return index of t in s, -1 if none */
int strindex(char s[], char t[]) {
   int i, j, k;

   for (i = 0; s[i] != '\0'; i++) {
      for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
         ;
      if (k > 0 && t[k] == '\0')
         return i;
   }
   return -1;
}

Result


Related Tutorials