/***
*char *strstr(string1, string2) - search for string2 in string1
*
*Purpose:
* finds the first occurrence of string2 in string1
*
*Entry:
* char *string1 - string to search in
* char *string2 - string to search for
*
*Exit:
* returns a pointer to the first occurrence of string2 in
* string1, or NULL if string2 does not occur in string1
*
*Uses:
*
*Exceptions:
*
*******************************************************************************/
char * __cdecl strstr (
const char * str1,
const char * str2
)
{
char *cp = (char *) str1;
char *s1, *s2;
if ( !*str2 )
return((char *)str1);
while (*cp)
{
s1 = cp;
s2 = (char *) str2;
while ( *s1 && *s2 && !(*s1-*s2) )
s1++, s2++;
if (!*s2)
return(cp);
cp++;
}
return(NULL);
}
/*同时,自己写的,朴素的查找子串算法*/
#include <iostream>
#include <stdio.h>
using namespace std;
char *mystrstr(char *string, char *substring)
{
char *pstr = string;
char *tmpstr, *psub;
//外循环是主串不到末尾则一直do
while (*pstr) {
tmpstr = pstr;
psub = substring;
//从主串的某个位置开始,判断其后的字符串是否为子串。
while (*tmpstr && *psub && !(*tmpstr - *psub)) {
tmpstr++;
psub++;
}
if (!(*psub)) {
return pstr;
}
//主串对比位置后移一个字符。
pstr++;
}
return NULL;
}
int main()
{
char s1[20] = "helloworld";
char s2[10] = "wo";
cout << mystrstr(s1, s2);
}