Rahul Mayuranath
Rahul Mayuranath

Reputation: 29

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

Upvotes: 0

Views: 72

Answers (2)

Sagar Patel
Sagar Patel

Reputation: 852

  • Try changing your for loop from this :

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

    to

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

Upvotes: 0

dbush
dbush

Reputation: 224002

As mentioned in the comments, when constructing comp, you're not adding a terminating null byte at the end. Because the rest of comp is not initialized, you invoke undefined behavior when calling strcmp.

Add the null byte at the end of the inner for loop will fix the problem:

     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:

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. Use fgets instead.

Upvotes: 2

Related Questions