先简单的看一下strstr的用法
#include <stdio.h>
#include <string.h>
int main()
{
const char str1[20] = "helloabcworld";
const char str2[10] = "world";
char *p = strstr(str1, str2);
printf("子字符串是: %s\n", p);
return(0);
}
假设字符串为abcdefgdnfaaaa我们要查找的字串为dnf,在指定的字符串中查找子串,如果有将子串出现的第一个字符位置返回(我们在下面用sum来接受它),如果没有则返回-1
//#include <stdio.h>
//#include <string.h>
//int main()
//{
// const char str1[20] = "helloabcworld";
// const char str2[10] = "world";
// char *p = strstr(str1, str2);
// printf("子字符串是: %s\n", p);
// return(0);
//}
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//参数1 原字符串 参数2 字串
int myStrstr(char *str,char * subStr)
{
int num = 0;
while (*str!='\0')
{
if (*str!=*subStr)
{
str++;
num++;
continue;
}
//如果相同的情况 即*str=*subStr 创建一个临时的指针
char *tmpStr = str;
char *tmpSubStr = subStr;
while (*tmpSubStr!='\0')
{
if (*tmpStr!=*tmpSubStr)
{
//匹配失败的情况
str++;
num++;
break;
}
//临时指针匹配相同情况
tmpStr++;
tmpSubStr++;
}
//字串到了'\0'则匹配成功
if (*tmpSubStr == '\0')
{
//匹配成功
return num;
}
}
return -1;
}
void test()
{
char *str = "abcdefgdnfadf";
int ret = myStrstr(str, "dnf");
if (ret != -1)
{
printf("找到了字串位置:%d\n",ret);
}
else
{
printf("没有找到字串\n");
}
}
int main()
{
test();
system("pause");
return EXIT_SUCCESS;
}