C++ 在字符串中查找子字符串,而这两个字符串都是用户输入
我编写了这个程序来查找字符串中的子字符串,而这两个字符串都是用户输入。虽然这种方法对这里的很多人来说可能是业余的,但效果很好。我的问题是,当我将字符串“a”和“b”分别放在下面:“我是kamlesh”和“am”。 在给出输出3和7的最后一个if语句中省略“a[t4]=''”时,我没有得到任何输出。 请建议一些纠正方法,并仅将输出设置为3。 后期编辑:现在工作正常C++ 在字符串中查找子字符串,而这两个字符串都是用户输入,c++,string,substring,C++,String,Substring,我编写了这个程序来查找字符串中的子字符串,而这两个字符串都是用户输入。虽然这种方法对这里的很多人来说可能是业余的,但效果很好。我的问题是,当我将字符串“a”和“b”分别放在下面:“我是kamlesh”和“am”。 在给出输出3和7的最后一个if语句中省略“a[t4]=''”时,我没有得到任何输出。 请建议一些纠正方法,并仅将输出设置为3。 后期编辑:现在工作正常 /* #include <iostream> #include<cstdio> #include<cst
/* #include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
void substring(char *a,char *b);
int main()
{
char a[80],b[80];
gets(a);
gets(b);
substring(a,b);
return 0;
}
void substring(char *a,char *b)
{
int c,d;
c=strlen(a);
d=strlen(b);
for(int t=0;t<c;t++)
{
if(a[t] && a[t]==*b)
{
int t1,t2,t3,t4;
t2=1;
t1=d-1;
t3=t+1;
while(t1 && a[t3]==b[t2] )
{
t1--;
t3++;
t2++;
t4=t2;
}
if(!t1 && a[t4]==' ') //to avoid showing "am" in kamlesh.
cout<<t+1<<endl;
}
}
} */
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
void substring(char *a,char *b);
int main()
{
char a[80],b[80];
int s;
gets(a);
gets(b);
substring(a,b);
return 0;
}
void substring(char *a,char *b)
{
char *s1,*s2;
for(int t=0;a[t];t++)
{
s1=&a[t];
s2=b;
while(*s2 && *s2==*s1)
{
s1++;
s2++;
}
if(*s2 && *s1==' ')
cout<<t;
}
}
/*#包括
#包括
#包括
使用名称空间std;
无效子字符串(char*a,char*b);
int main()
{
字符a[80],b[80];
获得(a);
获取(b);
子串(a,b);
返回0;
}
无效子字符串(char*a,char*b)
{
int c,d;
c=斯特伦(a);
d=斯特伦(b);
对于(int t=0;t,正如donjuedo所说,这段代码非常不可读。我很快就看到[t4]是有问题的,因为不能保证t4会在那之前初始化;您不需要从子字符串(t1)的末尾向后走;并且您不需要使用整数索引来遍历字符串,您可以四处移动指针
代码应该简单到:
char*p1=(char*)str;//要搜索的字符串
int substrIndex=0;
而(*p1){
char*p1Begin=p1;//保留搜索开始的位置
char*p2=(char*)目标;//子字符串的指针
而(*p1&&*p2&&*p1==*p2){//只要在边界内,字符就等于
p1++;
p2++;
}
if(!*p2)//如果所有字符相等,则通过目标末尾-成功
这就像一个谜。变量名没有任何意义,而且很难理解。几乎没有任何评论来描述您正在采取的方法。我认为,如果您解决了这些问题,您将不需要任何帮助——您的问题可能会变得明显,解决方案也很容易。不要用“修复”来编辑您的问题这让它消失了!相反,如果没有人回答你的问题,而你确实找到了“答案”,请将其作为答案发布!对不起,我会记住这一点。
char* p1 = (char*)str; // the string to be searched
int substrIndex = 0;
while (*p1) {
char* p1Begin = p1; // keep the pos of start of search
char* p2 = (char*)target; // pointer for the substring
while (*p1 && *p2 && *p1 == *p2) { // as long as within the boundaries, chars equal
p1++;
p2++;
}
if (!*p2) // if all chars equal, passed end of target - success
cout << substrIndex << endl;
p1 = p1Begin + 1;
substrIndex++;
}