简体   繁体   English

查找字符串中给定子字符串的出现次数

[英]Issue finding number of occurrences of a given substring in a string

The below code always returns number of matching sub strings as zero.There are no errors in the code and i am not sure where have i gone wrong logically. 下面的代码始终将匹配的子字符串的数量返回为零。代码中没有错误,我不确定逻辑上哪里出错了。

#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 ;
}  

As mentioned in the comments, when constructing comp , you're not adding a terminating null byte at the end. 如注释中所述,在构造comp ,您不会在末尾添加一个终止的空字节。 Because the rest of comp is not initialized, you invoke undefined behavior when calling strcmp . 由于comp的其余部分未初始化,因此在调用strcmp时会调用未定义的行为。

Add the null byte at the end of the inner for loop will fix the problem: 在内部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';

Actually, rather than creating a separate substring, just use strncmp , which compares up to a certain number of characters: 实际上,与其创建单独的子字符串, 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++ ; }
 }

Also, don't use gets , as that is prone to buffer overflows. 另外,不要使用gets ,因为这样容易导致缓冲区溢出。 Use fgets instead. 请改用fgets

  • Try changing your for loop from this : 尝试从此更改for循环:

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

    to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM