[英]Issue finding number of occurrences of a given substring in a string
下面的代碼始終將匹配的子字符串的數量返回為零。代碼中沒有錯誤,我不確定邏輯上哪里出錯了。
#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 ;
}
如注釋中所述,在構造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
使用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
。
嘗試從此更改for循環:
for ( i=0 ; i < strlen(str) - len ; i++ )
至
for ( i=0 ; i <= strlen(str) - len ; i++ )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.