strstr函数
strstr函数:strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。
源函数:
#include <stdio.h>
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 (*s2 && !(*s1 - *s2))
s1++, s2++;
if (!*s2)
return(cp);
cp++;
}
return(NULL);
}
int main(int argc, char *argv[], char *envp[])
{
char str[] = "asfasfas";
char *p = "asas";
char ret = '0';
ret = strstr(str, p);
if (ret != NULL)
{
printf("%c", ret);
}
else
{
printf("NULL");
}
return 0;
}
自己的strstr函数
//自己的strstr函数
char * __cdecl my_strstr(const char *str1, const char *str2)
{
char *cur = (char *)str1;
char *s1 = NULL;
char *s2 = NULL;
if (!*str2)
{
return ((char *)str1);
}
while (*cur)
{
s1 = cur;
s2 = (char *)str2;
while (*s2 && !(*s1 - *s2)) //*s2不为空,并且*s1要与*s2相等
{
s1++;
s2++;
}
if (!*s2)
{
return cur;
}
cur++;
}
return NULL;
}
如有不足:请告诉小凯,会及时更新与修改的,谢谢大家
如果对github感兴趣可以到我的github中看一下.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)