###########################################
目录
前言
在C的标准库<string.h>中提供了字符串匹配函数,C 库函数 char *strstr(const char *haystack, const char *needle) 在字符串 haystack 中查找第一次出现字符串 needle 的位置,不包含终止符 '\0'。
一、使用sscanf从字符串读取格式化输入函数重写
sscanf是C标准库<stdio.h>提供的字符串格式化读取函数,声明为
int sscanf(const char *str, const char *format, ...)
二、重写的函数
- 使用sscanf重写的函数
char* myStrstr(char * str,char * subStr)
{
char buf[1] = {0};
char temp[100] = {0};
strcpy(temp,subStr);
if(strlen(temp) == 0)
{
return NULL;
}
temp[strlen(temp)+1] = temp[strlen(temp)-1];
temp[strlen(temp)-1] = '%';
temp[strlen(temp)] = '[';
temp[strlen(temp)] = ']';
while(* str !='\0')
{
sscanf(str,temp,buf);
if(buf[0]==temp[strlen(temp)-2])
return str;
str++;
}
return NULL;
}
2.使用指针重写的函数
char* Strstr(char * str,char * substr)
{
while(* str!='\0')
{
char * tempstr = str;
char *tempsubstr = substr;
if(*str == *substr)
{
while(*tempsubstr !='\0')
{
if(*tempstr!=*tempsubstr)
{
break;
}
tempstr++;
tempsubstr++;
}
if(*tempsubstr == '\0')
return str;
}
str++;
}
return NULL;
}
3.使用memcmp重写的函数
char* newStrstr(char * str,char * substr)
{
int length = strlen(substr);
while(*str != '\0')
{
if(memcmp(str,substr,length)==0)
return str;
str++;
}
return NULL;
}
总结
我们这里使用的这种方法比使用额外指针的方法更加清晰一些,实现的功能和标注库提供的strstr()函数一样,希望对你有一定的帮助。