2015-05-24 34 views
-3

嘿家伙,我已经提出,应该找到主串子串的功能,但它不能正常工作,这里是代码:C++查找字符串代码,逻辑错误

char *mystrstr (char *s1, char *s2) 
{ 
    int i=0, j=0, k=0,t=0, l; 
    char* s3 = NULL; 
    char* s4 = NULL; 
    l = mystrlen (s2); 
    k = mystrlen(s1); 

    //s1 is the main string and s2 is the substring 
    if (*(s1 + i) == '\0') //checks if the main string is not null. 
     return s1; 



    while (*(s1 + i) != '\0' && *(s2 + i) != '\0')// if both the strings are not null then the program proceeds 

     { 
      while (s1[i] != s2[0] && s1 != NULL)//loop runs till the first letter of substring is found in the main string. 
      { 
       i++; 
      } 

      if (*(s1 + i) == '\0') 
       return NULL; 

      t = i;//stores the position where the first substrign was found 
      while (s1[i] == s2[j] && s1[i] != '\0' && s2[j] != '\0') 
      { 
       i++;//takes tho the nextl letter of the main string 
       j++;//to the next letter of the substring. 
      } 
     } 
    if (l == j)//if all letters of the substring is found in the main string only then this condition will be true. 
    { 
     s3 = &s1[t]; 
    } 
    return s3; 
} 

能任何人都会说出什么不对,或者至少给我一个提示?

所以根据给出的建议我改变了我的代码,它给了我想要的结果。这是新代码 -

的char * mystrstr(字符* S1,字符* S2) {

int i = 0, j = 0, k = 0, t = 0, l; 
char* s3 = NULL; 
char* s4 = NULL; 
l = strlen(s2); 
k = strlen(s1); 

if (*(s1 + i) == '\0' && *(s2 + i) != '\0') 
    return NULL; 

if (*(s1 + i) != '\0' && *(s2 + i) == '\0') 
    return s1; 

if (*(s1 + i) == '\0') 
    return s1; 


while (*(s1 + i) != '\0') 
{ 
    while (s1[i] != s2[j] && s1 != NULL) 
    { 
     i++; 
     j = 0; 
    } 
    if (*(s1 + i) == '\0')return NULL; 
    t = i; 
    while (s1[i] == s2[j] && s1[i] != '\0'&&s2[j] != '\0') 
    { 
     i++; 
     j++; 
    } 
    if (l == j){ 
     s3 = &s1[t]; 
     return s3; 
    } 
} 
return NULL; 

}

反正有做使代码更高效。我使用此代码来查找主字符串形式的子字符串。

+0

对于英语不好的人感到抱歉 – user3458561

+0

用调试程序遍历代码。 –

+1

为什么不使用'std :: string'类中的'substr'? – Caduchon

回答

1

你在这一行中的错误:

while (*(s1 + i) != '\0' && *(s2 + i) != '\0') 

这将不存在,除非在字符串的非常相同位置的'\0'。您应该使用||,并且还应该考虑索引。也许你想用j来索引s2

if (*(s1 + i) == '\0') 
       return NULL; 

上面的代码,当你达到s1结束返回NULL。如果s2恰好在s1的末尾,会发生什么情况?它将返回NULL。所以这是另一个bug,因为它假设如果你到达字符串的末尾,那么子字符串没有找到。

您还应该检查ij的进展情况。如果它没有退出while循环,那么它永远不会到达return。如果您使用“运行到游标”来调试您的return语句,那么调试器是否跳到那里?如果该程序没有永久运行,那么它最终会停止,因此它不会永远运行您的while。你应该检查所有这些。

我只是给你一些想法如何解决问题,我不想解决你的功课。

+0

感谢您帮助我尝试更改代码,但它不起作用。如果我将主字符串输入为“llamq”,子字符串输入为“am”,那么t应该是2,但它是4.所以我认为我需要做出更多的改变,但是谢谢你。 – user3458561

+0

是的,你需要改变一些东西。但永远不要告诉我们有什么不工作。始终描述你所经历的确切行为。 –

+0

嘿,我确实改进了我的代码,它也给我所需的结果。如果这对你来说不是问题,你能否请你判断我的代码,告诉我它是多么的渺茫,还是有更好的方法去做。您无需完全写出如何改进我的代码,只需告诉我它是多么的渺茫。谢谢你的帮助。 – user3458561