输入两个字符串判断第二个字符串是不是第1个字符串的子串 用C语言怎么编写这个程序

如题所述

#include <stdio.h>

int isstr(const char *source,const char *dest)
{
int i=0,j,k;
while(source[i]!='\0')
{
k=i;j=0;
while(source[k]!='\0'&&dest[j]!='\0'&&source[k]==dest[j])
k++,j++;
if (dest[j]=='\0')
return 1;
if (source[k]=='\0')
return 0;
i++;
}
return 0;
}

int main()
{
char data[] = "ni hao";
char data1[] ="hao";
printf("%d\n",isstr(data,data1));
return 0;
}
程序如上,关键函数就是
int isstr(const char *source,const char *dest)
判断dest字符串是否是source的子串。
是,返回1,否则返回0.
有问题可以空间留言,或hi我。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-06-25
/* STRSTR.C */

#include <string.h>
#include <stdio.h>

char fmt1[] = "12345 ";
char fmt2[] = "12345678901234567890123456789012345678901234567890 ";

void main( void )
{
char *pdest;

pdest = strstr( fmt2, fmt1 );

if( pdest != NULL )

//是字串

else

//不是子串

}
第2个回答  2010-06-25
#include <stdio.h>
#include <string.h>

void main()
{
char main_str[20],zi_str[10];
int i=0,j=0,count,r=0,k;
printf("Please input the first string-->");
gets(main_str);
printf("\nPlease input the second string-->");
gets(zi_str);
count=strlen(zi_str);
while(main_str[i])
{
k=i;
while(main_str[i]==zi_str[j])
{
i++;
j++;
if(count==j)
{
++r;
printf("\nYes...");
goto end;
}
}
j=0;
i=k+1;
}
end:
if(!r)
{
printf("\nNo...");
}
getch();
}
第3个回答  2010-06-25
#include<stdio.h>
#include<string.h>
#define MaxSize 100
typedef struct
{
char data[MaxSize];
int length;
}String;
int BFindex(String S,String T,int start)
{
int i=start,j=0,v;
while(i<S.length&&j<T.length)
{
if(S.data[i]==T.data[j])
{
i++;
j++;
}
else
{
i=i-j+1;
j=0;
}
}
if(j==T.length)v=i-T.length;
else
v=-1;
return v;
}
int main()
{
String S,T;
int start=0,i=0,v;
printf("请输入主串:");
gets(S.data);
S.length=strlen(S.data);
i=0;
printf("请输入子串:");
gets(T.data);
T.length=strlen(T.data);
v=BFindex(S,T,0);
if(v==-1)
printf("不在里面!\n");
else
printf("从第%d个字符开始匹配成功!\n",v+1);
return 0;
}
/*这是一种算法...也可以用KMP算法...具体百度一下就知道了....*/