2015-05-24 58 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