一、思路
1.硬解。找到第一个匹配字符,通过判断后续字符是否匹配直接判断,若后续不对则直接后移
2.通过指针。创建两个临时指针分别指向目标串和源串,依次移动,设置计数器可返回下标
二、代码
// 从abcdefgdnfxyz中查找子串str=“dnf”,有返回d下标,无返回-1
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
void test()
{
char *s = "abcdefgdnfxyz";
// int len = sizeof(s) / sizeof(char); 错误代码
int len = strlen(s);
for (int i = 0; i < len; i++)
{
if (s[i] == 'd' && s[i + 1] == 'n' && s[i + 2] == 'f')
{
printf("%d\n", i);
break;
}
if (i == len - 1)
{
printf("-1\n");
break;
}
}
}
int myStr(char *str, char *subStr)
{
int n = 0;
while (*str != '\0')
{
if (*str != *subStr)
{
str++;
n++;
continue;
}
// 创建两个临时指针
char *tmp1 = str;
char *tmp2 = subStr;
while (*tmp2 != '\0')
{
if (*tmp1 != *tmp2)
{
str++;
n++;
break;
}
tmp1++;
tmp2++;
if (*tmp2 == '\0')
{
return n;
}
}
}
return -1;
}
void test1()
{
char *s = "abcdefgdnfxyz";
int ret = myStr(s, "dnf");
if (ret != -1)
{
printf("%d\n", ret);
}
else
{
printf("NO");
}
}
int main()
{
test1();
system("pause");
return 0;
}