#include <stdio.h>
#include <string.h>
char *bxy_strstr(const char *s1, const char *s2)
{
int len2;
if (!(len2 = strlen(s2)))
{
return (char *)s1;
}
for ( ;*s1; ++s1)
{
if (*s1==*s2 && strncmp( s1, s2, len2 ) == 0)
{
return (char *)s1;
}
}
return NULL;
}
int main(void)
{
char *str1 = "Borland International. Welcome to nation.", *str2 = "nation", *ptr;
ptr = bxy_strstr(str1, str2);//返回str2在str1里第一次出现的位置处的指针。
printf("The substring is: %s\n", ptr);
return 0;
}
The substring is: national. Welcome to nation.
请按任意键继续. . .The substring is: national. Welcome to nation.
请按任意键继续. . .
#include <stdio.h>
#include <assert.h>
char *myStrstr(const char *str1, const char *str2)
{
assert(str1 !=NULL && str2 != NULL);
if (str1 == str2) //如果两指针指向同一地址,直接返回str1
{
return (char *)str1;
}
char *s1, *s2;
while (*str1) //str1用于记录找到子串的位置
{
s1 = (char *)str1;
s2 = (char *)str2;
//当str2中有字符与str1中的相同并且str1和str2都未至末尾时,循环
while ((*s1 == *s2) && *s1 && *s2)
{
s1++;
s2++;
}
//如果str2已经遍历至末尾('/0')时,说明在str1中找到了子串str2
if ('\0' == *s2)
{
return (char *)str1; //返回找到的位置
}
str1++;
}
/* 查找不成功,返回NULL */
return NULL;
}
void main(int argc,char *argv[])
{
char *a ="aaHello worldHello!";
char *b = "Hello";
char *d= myStrstr(a,b);
printf("%s\n", d);
}
#include <stdio.h>
#include <assert.h>
char *strstr_mf(const char *str1, const char *str2)
{
assert(str1 !=NULL && str2 != NULL);
//如果两指针指向同一地址,直接返回str1
if (str1 == str2)
{
return (char *)str1;
}
//str1用于记录找到子串的位置
while (*str1)
{
char *s1 = (char *)str1;
char *s2 = (char *)str2;
//当str2中有字符与str1中的相同并且str1和str2都未至末尾时,循环
while ((*s1 == *s2) && *s1 && *s2)
{
s1++;
s2++;
}
//如果str2已经遍历至末尾('/0')时,说明在str1中找到了子串str2
if ('\0' == *s2)
{
return (char *)str1; //返回找到的位置
}
str1++;
}
return NULL;
}
void main(int argc,char *argv[])
{
char *a ="asdHello world!";
char *b = "llo";
char *d= strstr_mf(a,b);
printf("%s\n", d);
}