C语言实现字符串中查找字符串

时间:2021-12-27 06:21:49
查找字符串函数实现:
//find string in string, return the first start location or -1 if can not find
int StringFind(const char *pSrc, const char *pDst)
{
int i, j;
for (i=0; pSrc[i]!='\0'; i++)
{
if(pSrc[i]!=pDst[0])
continue;
j = 0;
while(pDst[j]!='\0' && pSrc[i+j]!='\0')
{
j++;
if(pDst[j]!=pSrc[i+j])
break;
}
if(pDst[j]=='\0')
return i;
}
return -1;
}

测试代码:

#include <stdio.h>

int main(){
  char* t = "ffdsssssssssddddddflowerdddddd";
  printf("字符串第一次出现位置:%d\n",StringFind(t,"flower"));
  getchar();
  return 0;
}