有一个在给定字符串中查找子串的函数strstr,该函数从给定的字符串src中查找substr并返回一个整数,指明substr第一次出现的位置(从0开始计数),如果找不到则返回-1。
要求:
1、实现该函数。
2、为该函数设计与实现单元测试。
说明:
1、代码中不允许使用系统已有的库函数,所有用到的库函数都需要自己实现
2、允许使用任何编程语言,函数原型自行给定。参考的C语言函数原型为 int strstr(char* src , char* substr)
#include<stdio.h>
int strstr(char* src , char* substr)
{
int location=-1;
int len_src;
int len_subsrc;
int i,j;
i=0;
while (src[i]!='\0')
{
i++;
}
len_src=i;
j=0;
while (substr[j]!='\0')
{
j++;
}
len_subsrc=j;
printf("%3d,%3d\n",len_src,len_subsrc);
i=0;
while(len_src-i>len_subsrc)
{
j=0;
while((substr[j]==src[i])&&(substr[j]!='\0'))
{
printf("%c,%c\n",src[i],substr[j]);
j++;
i++;
}
if(j==0)
{
i++;
}
printf("----------\n");
if(j==len_subsrc)
{
location=i-j;
break;
}
}
if(location!=-1)
return location;
else
return -1;
}
void main()
{
char *src="ahdgsgabcwehdaj";
char *substr="abcwe";
//strstr(src,substr);
int result=strstr(src,substr);
printf("%3d\n",result);
}
转载于:https://blog.51cto.com/8734514/1557783