Problem:
Function Name: strstr function prototype: char * strstr (const char * str1, const char * str2); Syntax: * strstr (str1, str2) str1: target string expression to search. str2: the string expression to find. return Value: This function returns the address of str2 in str1 for the first time. If no address is found, the return value is null:
charstr[]=
"1234xyz"
;
char
*str1=
strstr
(str,
"34"
);
Get str1 = "34xyz"
Method 1:
One pointer scan, when the first letter is the same, the two pointers scan two strings for comparison.
The Code is as follows:
#include <stdio.h>#include <string.h>#include <assert.h>char* mystrstr(const char* str1,const char* str2)//str1 is the original string { assert(str1 != NULL); if(str2 != NULL) return (char*)str1; while(str1 != ‘\0‘){ if(*str1 != *str2) str1++; else{ char* ori = str1; char* des = str2; while(*des != ‘\0‘){ if(*ori == *des){ ori++;des++; } else break; } if(*des == ‘\0‘) return str1; } } return NULL;}int main(){ char ori[]="sdggdfhhttyusdfge"; char des[]="ttyu"; char* ret=mystrstr(ori,des); printf("%s\n", ret); return 0;}
The result is
[[Email protected] desktop] #./A. Out
Ttyusdfge
Method 2:
Similar methods:
#include <stdio.h>#include <string.h>char* mystrstr(const char* str1,const char* str2)//str1 is the original string { int len2 = strlen(str2); int len1 = strlen(str1); if(!len2) return (char*)str1; while(len1 >= len2){ len1--; if(!strcmp(str1,str2,len2)) return (char*)str1; str1++; } } return NULL;}int main(){ char ori[]="sdggdfhhttyusdfge"; char des[]="ttyu"; char* ret=mystrstr(ori,des); printf("%s\n", ret); return 0;}
The result is
[[Email protected] desktop] #./A. Out
Ttyusdfge
String substring search strstr