下面的代碼始終將匹配子字符串的數量作爲零返回。代碼中沒有錯誤,我不確定邏輯上哪裏出錯了。發現字符串中給定子字符串的出現次數
#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 ;
}
此代碼沒有任何意義。爲什麼您需要首先製作子字符串的副本? – Lundin
使用fgets而不是獲取,除非有很好的理由。 – ForeverStudent
使用調試器或至少打印您檢查的數據。 – Olaf