char *_mystr(const char* _str, const char* _dst)
{
//int _num = 0;
while (*_str != '\0')
{
if (*_str != *_dst)
{
_str++;
//_num++;
continue;
}
//创建临时指针
char* _tempstr = _str;
char* _tempdst = _dst;
while (*_tempdst != '\0')
{
//匹配不成功
if (*_tempstr != *_tempdst)
{
_str++;
//_num++;
break;
}
_tempstr++;
_tempdst++;
}
//匹配成功
if (*_tempdst == '\0')
return _str;
}
return NULL;
}
int main()
{
char* _str = "abcdefgdnfaaaaaaa";
char* _ret = _mystr(_str, "dnf");
if (_ret == NULL)
{
printf("匹配失败!\n");
}
else
{
printf("%s\n", _ret);
}
return 0;
}
运行结果:
详细讲解:
while (*_str != '\0')
{
if (*_str != *_dst)
{
_str++;
continue;//跳过本次循环,继续下次循环
}
}
1.*_str != *_dst 假设两个指针首字母不相等,让_str继续查找,直到与_dst首字母相匹配为止
//创建临时指针
char* _tempstr = _str;
char* _tempdst = _dst;
while (*_tempdst != '\0')
{
//匹配不成功
if (*_tempstr != *_tempdst)
{
_str++;
break;//退出子循环
}
_tempstr++;
_tempdst++;
}
2.第一步已经匹配到首字母相同,创建两个临时指针对后面的字符在进行二次比较,直至全部字符匹配为止,如果后面字符不匹配则退出子循环while (*_tempdst != ‘\0’),
//匹配成功
if (*_tempdst == '\0')
{
return _str;
}
3.如果_tempdst最后 == \0,就是要查找字符串”dnf” 与_tempstr全部匹配,这个时候就是可以返回_str指针了,这就是定义临时指针好处。
版权声明:本文为xjm956原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。