2015-08-26 33 views
-1

我已经写了这个程序来查找字符串中的子字符串,而他们都是用户inputs.This工作正常,虽然方法可能似乎业余相当一个这里很少。我的问题是,当我把字符串“a”和“b”分别如下:“我是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; 
    } 

    } 
+0

这就像一个谜题。变量名称没有意义,并且很难遵循。几乎没有评论来描述你正在采取的方法。我认为如果你清除这些问题,你就不需要任何帮助 - 你的问题可能会变得明显,解决方案也很容易。 – donjuedo

+0

不要编辑你的问题与“修复”,使它消失!相反,如果没有anwers回答你的问题,你确实找到了“答案”,将其作为答案张贴! – crashmstr

+0

对不起,我会牢记这一点。 –

回答

0

正如donjuedo所说,这段代码是非常不可读的。我很快看到的事情是,[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%肯定它会运行无bug;但你明白了。