本文介绍了该程序用于查找主串中子串的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
只是没有得到正确的输出..
逻辑是正确但无法找到错误。
如果我输入任何字符串和子字符串,输出只是一个
未找到子串..
plz帮助我
我尝试过:
just doesn't get right output ..
the logic is right but can't find the bug.
if i enter any string and substring,the output is just one
Substring not found..
plz help me
What I have tried:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
int i,j,pos,flag;
char sub[100],main[100];
cout<<"enter main string"<<endl;
gets(main);
cout<<"enter substring"<<endl;
gets(sub);
for(i=0;main[i]!='\0';++i)
{
if(main[i]==sub[0])
{
pos=i,j=0;
while(sub[j]==main[i])
{
i++ ;
j++;
}
}
if(j==strlen(sub))
flag=1;
else
flag=0;
}
if(flag== 1)
cout<<"substring found at"<<pos+1<<endl;
if(flag==0)
cout<<"substring not found" ;
getch();
}
推荐答案
if(main[i]==sub[0])
{
pos=i,j=0;
// Check for end of string too
while(sub[j]==main[i] && main[i] != '\0')
{
i++;
j++;
}
// Moved this into if condition
if(j==strlen(sub))
flag=1;
else
flag=0;
// Restore i here
i = pos;
}
引用:
if(j == strlen(sub))
flag = 1;
if(j==strlen(sub))
flag=1;
to
to
if(j==strlen(sub))
{
flag=1;
break;
}
你也错过了代码中的字符串结束检查,从
You also miss end-of -tring checking in your code, chage from
Quote:
while(sub [j] == main [i])
while(sub[j]==main[i])
to
to
while(main[i] != 0 && sub[j]==main[i])
另请注意,您使用的是过时的编译器和不推荐使用的函数。
Note, also, you are using an outdated compiler and deprecated functions.
这篇关于该程序用于查找主串中子串的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!