1.strstr function Description
The Strstr () function searches for the first occurrence of a string in another string. When the searched string is found, the function returns the address of the first matching string, or null if the searched string is not found
2.strstr function Application
#include <stdio.h>#include<stdlib.h>#include<string.h>voidMain () {Charstr1[9] ="tasklist"; Charstr2[5]="List"; Char*p =strstr (str1, str2); if(p) {puts ("include"); } Else{puts ("does not contain"); } System ("Pause");}
3. Ideas
4. Subscript implementation
#include <stdio.h>#include<stdlib.h>#include<string.h>Char*MYSTRSTR (Char*STR1,Char*str2) { Char*p =NULL; intLENSTR1 = strlen (STR1);//Length of str1 intLENSTR2 = strlen (STR2);//Length of str2
if (LENSTR1<LENSTR2) return p; //LENSTR1-LENSTR2 indicates that STR1 will be out of bounds when the number of characters remaining in str1 is <STR2 for(inti =0; I <=lenstr1-lenstr2; i++) { intFind =1;//identity found or not for(intj =0; J < Lenstr2; J + +) { //why I+j? Because both str1 and str2 move in sync. if(Str1[i + j]! =Str2[j]) {Find=0; Break;//Jump out of internal for loop } } if(find==1) {p= &str1[i];//returns the address where the first str2 occurred Break;//description has been found } } returnp;}voidMain () {Charstr1[9] ="tasklist"; Charstr2[5]="List"; Char*p =mystrstr (str1, str2); if(p!=NULL) {Puts ("include"); printf ("%c", *p); } Else{puts ("does not contain"); } System ("Pause");}
5. Pointer implementation
#include <stdio.h>#include<stdlib.h>#include<string.h>Char*MYSTRSTR (Char*STR1,Char*str2) { Char*p =NULL; if(Strlen (STR1) < strlen (STR2))returnp; for(Char* Pstr1 = str1; *pstr1! =' /'; pstr1++) { intFind =1; for(Char* PSTR2 = str2; *pstr2! =' /'; pstr2++) { //prevent cross-border if(* (Pstr1 + (pstr2-str2)) = =' /') {Find=0; Break; } if(* (Pstr1 + (PSTR2-STR2))! = *pstr2) {Find=0; Break; } } if(find==1) {p=pstr1; Break; } } returnp;}voidMain () {Char*STR1 ="tasklist"; Char*STR2 ="List"; Char*p =mystrstr (str1, str2); if(p!=NULL) {Puts ("include"); printf ("%c", *p); } Else{puts ("does not contain"); } System ("Pause");}
11th Day of Learning C (STRSTR function implementation)