2016-01-27 64 views
0

下面的代碼始終將匹配子字符串的數量作爲零返回。代碼中沒有錯誤,我不確定邏輯上哪裏出錯了。發現字符串中給定子字符串的出現次數

#include<stdio.h> 
#include<string.h> 

int main() 
{ 
    int i,j,len ,k ,count, num ; 
    char str[100],sub[100],comp[100] ; 
    // sub is the sub string . 
    printf("Please enter the string") ; 
    gets(str) ; 
    printf("Enter the substring to be searched for") ; 
    gets(sub) ; 
    len=strlen(sub) ; 
    for (i=0 ; i < strlen(str) - len ; i++) 
    //Goes till length of string - length of sub string so that all characters can be compared. 
     { 
     num = i + len ; 
     for (j=i,k=0 ; j<num ; j++, k++) 
     //Loop to store each sub string in an array comp. 
      { 
      comp[k]=str[j] ; 
      } 
     if (strcmp(comp,sub) == 0) 
      { count++ ; } 
    } 
    printf("no of occurances is:%d",count) ; 
    return 0 ; 
} 
+0

此代碼沒有任何意義。爲什麼您需要首先製作子字符串的副本? – Lundin

+0

使用fgets而不是獲取,除非有很好的理由。 – ForeverStudent

+0

使用調試器或至少打印您檢查的數據。 – Olaf

回答

2

正如在評論中提到,建設comp的時候,你不是在末處加入終止空字節。由於comp的其餘部分未初始化,因此調用strcmp時會調用未定義的行爲。

在內部for循環的末尾添加空字節將解決這個問題:

 for (j=i,k=0 ; j<num ; j++, k++) 
    //Loop to store each sub string in an array comp. 
     { 
     comp[k]=str[j] ; 
     } 
    comp[k] = '\0'; 

事實上,而不是創建一個單獨的子串,只是使用strncmp,與之相比,達到一定數目的字符:

for (i=0 ; i < strlen(str) - len ; i++) 
//Goes till length of string - length of sub string so that all characters can be compared. 
    { 
    if (strncmp(&str[i],sub,strlen(sub)) == 0) 
     { count++ ; } 
} 

另外,不要使用gets,因爲這很容易出現緩衝區溢出。改爲使用fgets

+0

注意:由於比較不會超過字符串的長度,因此代碼使用'memcmp(&str [i],sub,...)'可能會使用長字符串YMMV更快。 – chux

+0

對於像我這樣的初學者來說,這非常有幫助。謝謝 ! –

+0

@RahulMayuranath很高興我能幫到你。如果您覺得它有用,請隨時[接受此答案](http://stackoverflow.com/help/accepted-answer)。 – dbush

0
  • 嘗試從此改變你的for循環:

    for (i=0 ; i < strlen(str) - len ; i++) 
    

    for (i=0 ; i <= strlen(str) - len ; i++) 
    
相關問題