Simply put, you can compare strings from the first location to the next until they are not the same. In this case, the relationship between the same number of characters and the length of the substring is compared, returns the first location with the same position; otherwise, returns-1.
1 #include<stdio.h> 2 3 int find_substr(char *mainstr,char *substr); 4 5 int main(void) 6 { 7 if(find_substr("C is fun!","is")==-1) 8 { 9 printf("substr is not found!\n");10 }11 else12 {13 printf("substr is found!\n");14 }15 return 0;16 }17 18 int find_substr(char *mainstr,char *substr)19 {20 char *temp=substr;21 int size=0;22 23 while(*temp)24 {25 ++size;26 ++temp;27 }28 29 int no=0;30 31 while(*substr!=*mainstr)32 {33 ++no;34 ++mainstr;35 }36 37 int index=0;38 39 while(*(substr++)==*(mainstr++))40 {41 ++index;42 }43 44 if(index==size)45 {46 return no;47 }48 else49 {50 return -1;51 }52 }
Example in the book:
1 #include<stdio.h> 2 3 int find_substr(char *s1,char *s2); 4 5 int main(void) 6 { 7 if(find_substr("C is fun!","is")==-1) 8 { 9 printf("substr is not found!\n");10 }11 else12 {13 printf("substr is found!\n");14 }15 return 0;16 }17 18 int find_substr(char *s1,char *s2)19 {20 register int t;21 char *p,*p2;22 23 for(t=0;s1[t];++t)24 {25 p=&s1[t];26 p2=s2;27 28 while(*p2 && *p2==*p)29 {30 ++p;31 ++p2;32 }33 if(! *p2)34 {35 return t;36 }37 }38 return -1;39 }
In this example, the train of thought is:
Compare S2 and S1 until the end of S2 or the two are different. In this case, if the end of S2 is determined, the character position in the S1 string at the start of comparison is returned, otherwise, it ends because the two are different.-1 is returned;
Character array-returns the starting position of a substring in the string, without using the string header file-C