基础学习,巩固,为学习结构体做准备
/**************************************************************************编写一函数:int substring(char *str,char *sub),判断字符串sub是否是字符串str
的子串,若是子串,则返回子串位置,否则返回-1.
***************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int substring(char *str,char *sub)
{
int lena,lenb,i = 0,j = 0;
lena = strlen(str);
lenb = strlen(sub);
while(i < lena && j < lenb)
{
if(str[i] == sub[j])
{
j++;
i++;
}
else
{
i = i + 1 - j;
j = 0;
}
}
if(j >= lenb)
return i - lenb;
return -1;
}
int main(void)
{
char str[300];
char sub[300];
int m = 0;
printf("please input str:");
gets(str);
printf("please input sub:");
gets(sub);
m = substring(str,sub);
printf("m == %d\n",m);
if(m == -1)
printf("sub is not str son!\n");
else
printf("find the location is %d.\n",m);
return 0;
}