簡體   English   中英

查找字符串中給定子字符串的出現次數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM