Evelyn
QQ: 1809335179
strstr函数原型为 strstr(char* str,char* substr)
作用是在一个字符串中查找第一次出现的连续子串,如果存在返回字符串,不存在返回NULL
我这个实现的功能是返回第一次出现子串的位置
#include <iostream>
using namespace std;
int _strstr(char* str, char* substr) {
if (str == NULL || substr == NULL)
return -2^32;
int len1 = strlen(str);
int len2 = strlen(substr);
for (int i = 0; i < len1; i++) {
int j = 0;
while (str[i] == substr[j] && str[i] != '\0'&&substr[j] != '\0')
{
i++;
j++;
}
if (substr[j] == '\0')
return i-len2;
}
cout << "no match" << endl;
return -1;
}
void main() {
char* s1 = "abcdef";
char* s2 = "f";
int i=_strstr(s1, s2);
cout << i<<endl;
system("pause");
}
如果定义的是string ,调用strstr时需要将const char* 转换为char* ,可采用strcpy函数,调用形式为strcpy(dst,src)。