请教:如何在一个字符串中查找时候包含另一字符串。。。

kaniggia 2004-10-25 04:32:25
//如果sourcestr中包含substr,则返回TRUE.否则返回False.
//用纯C语言如何实现.另外有什么更好的办法呢?请各位大哥不吝赐教!!

Bool searchstr(char *sourcestr,char *substr)
{
int i=0,j=0;
int k=0;
for(j=0;j<(int)strlen(substr);j++)
{
if(sourcestr[i]==substr[j])
{ k++;
if(k==(int)(strlen(substr)-1))
return TRUE; 1
}
else
{
k=0;
j=0;
}
i++;
if(i>=(int)strlen(sourcestr))
return FALSE;
}
}
...全文
457 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
kaniggia 2004-10-27
  • 打赏
  • 举报
回复
OK了~~
谢谢各位!!
CSmaz_hand 2004-10-26
  • 打赏
  • 举报
回复
mark!
kaniggia 2004-10-26
  • 打赏
  • 举报
回复
感觉以上做法不是很理想,有没有更好的解决方案呢?在线等。。。
kaniggia 2004-10-25
  • 打赏
  • 举报
回复
多谢各位热心的大哥,我看一下先~~
lifan5748 2004-10-25
  • 打赏
  • 举报
回复
最简单的是KMP算法:

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


/****程序采用KMP字符串匹配法***/


void get_next(char *ch,int *next) /*求模式字符串每个字符的回溯值*/
{
int i=1,j=0;
while(i<strlen(ch))
{
if(j==0||ch[i]==ch[j]) { i++; j++; next[i]=j; }

else j=next[j];
}
}

int Index_kmp(char *str,char *ch,int *next) /*字符串匹配查询*/
{
int i=0,j=0;
while(j<strlen(ch)&&i<strlen(str))
{
if(str[i]==ch[j]) { j++; i++; }

else
{
if(j==0) i++;
else j=next[j];
}

}
if(j>=strlen(ch)) return (i-j+1);
else return 0;
}




void main()
{
FILE *fp;
char str[100],ch[100];
int i=0,next[100];
next[0]=100; next[1]=0;
if((fp=fopen("c:\\1.txt","r"))==NULL) /*这里根据需要进行修改*/
{
printf("File cann't be openen!");
exit(1);
}
while(!feof(fp))
str[i++]=fgetc(fp);
fclose(fp);
printf("Please input the string:\n");
gets(ch);
get_next(ch,next);
if((i=Index_kmp(str,ch,next))==0)
printf("Can't find the string!\n");
else
printf(" The string is finded in %s",&str[i-1]);
getch();
}
kobefly 2004-10-25
  • 打赏
  • 举报
回复
如果自己写的话
KMP算法可以考虑
pc2s 2004-10-25
  • 打赏
  • 举报
回复
char * strstr(const char * s1,const char * s2)
{
int l1, l2;

l2 = strlen(s2);
if (!l2)
return (char *) s1;
l1 = strlen(s1);
while (l1 >= l2) {
l1--;
if (!memcmp(s1,s2,l2))
return (char *) s1;
s1++;
}
return NULL;
}
kobefly 2004-10-25
  • 打赏
  • 举报
回复
库函数啊
char *strstr(const char *s1, const char *s2);
具体使用查找MSDN
carylin 2004-10-25
  • 打赏
  • 举报
回复
可以用STL算法就很方便了。比如includes算法。纯C语言实现有点麻烦!

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧