此算法原型是按照严蔚敏书第79页上的求子串位置的定位函数来写的,其实百度能看到很多关于字符串朴素算法的例子,其中不乏用c和c++语言实现的。不过大多数都是不带参数的,即要不是将串定义为全局的,要不就是在子函数中定义。而严蔚敏的书中是作为参数,并且带起始搜索位置的参数。
下面是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Index(char *str_1,char *str_2,int pos);
int main()
{
char str_1[] = "adhfgswdfa";
char str_2[] = "wd";
int fd = Index(str_1,str_2,2);
if(fd)
printf("The position is found\nThe position is %d\n",fd);
else
printf("The position is not found\n");
return 0;
} //main
int Index(char *str_1, char *str_2, int pos)
{
int len_1 = strlen(str_1);
int len_2 = strlen(str_2);
//printf("len_1=%d \t len_2=%d\n",len_1,len_2);
int i = pos-1;
int j = 0;
while( i <= (len_1-len_2) && j < len_2 )
{
if (str_1[i] == str_2[j])
{
++i;
++j;
}
else
{
i = i-j+1;
j = 0;
}
} //while
if ( j >= len_2-1 )
return i-len_2+1;
else
return 0;
} //Index
结果:
有一点是需要注意的,严蔚敏书中的写法是类似pascal的,因为她的数组的第0号位置存储的是数组大小,而标准c语言不是这样的,而我是按照c语言的风格来写的,数组起始也不是像她那样从1开始的,而是c语言中的0号位。不过结果是正常的,从1号位开始算的。