【问题标题】:Finding sub-string in a string while both of them are user inputs在字符串中查找子字符串,而它们都是用户输入
【发布时间】:2015-08-26 18:40:39
【问题描述】:

我已经编写了这个程序来查找字符串中的子字符串,而它们都是用户输入。这工作正常,尽管这里的方法可能看起来很业余。我的问题是当我把字符串“a " 和 "b" 分别为:"I am kamlesh" 和 "am"。 在给我输出 3 和 7 的最后一个 if 语句中省略“a[t4]==''”时,我没有得到任何输出。 请提出一些纠正方法并将输出仅作为 3。 后编辑:现在工作正常。

/* #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;
   }

  }

【问题讨论】:

  • 这就像一个谜题。变量名没有任何意义,而且很难理解。几乎有零个 cmets 来描述您正在采用的方法。我认为,如果您解决了这些问题,您将不需要任何帮助——您的问题可能会变得很明显,解决方案也很容易。
  • 不要用“修复”来编辑你的问题,让它消失!相反,如果没有答案回答您的问题而您确实找到了“答案”,请将其发布为答案!
  • 抱歉,我会记住这一点的。

标签: c++ string substring


【解决方案1】:

正如 donjuedo 所说,这段代码非常不可读。我很快看到的是 a[t4] 是有问题的,因为不能保证 t4 会在此之前被初始化;您不需要从子字符串 (t1) 的末尾向后走;并且您不需要使用整数索引在字符串中四处走动,您可以移动指针。

代码应该很简单:

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++;
}

我没有编译,所以不能 100% 确定它会运行无错误;但你明白了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 2011-07-13
    相关资源
    最近更新 更多