c - Issue finding number of occurrences of a given substring in a string -
the below code returns number of matching sub strings zero.there no errors in code , not sure have 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 sub string . printf("please enter string") ; gets(str) ; printf("enter substring searched for") ; gets(sub) ; len=strlen(sub) ; ( i=0 ; < strlen(str) - len ; i++ ) //goes till length of string - length of sub string characters can compared. { num = + len ; ( j=i,k=0 ; j<num ; j++, k++ ) //loop store each sub string in array comp. { comp[k]=str[j] ; } if ( strcmp(comp,sub) == 0 ) { count++ ; } } printf("no of occurances is:%d",count) ; return 0 ; }
as mentioned in comments, when constructing comp
, you're not adding terminating null byte @ end. because rest of comp
not initialized, invoke undefined behavior when calling strcmp
.
add null byte @ end of inner for
loop fix problem:
( j=i,k=0 ; j<num ; j++, k++ ) //loop store each sub string in array comp. { comp[k]=str[j] ; } comp[k] = '\0';
actually, rather creating separate substring, use strncmp
, compares number of characters:
for ( i=0 ; < strlen(str) - len ; i++ ) //goes till length of string - length of sub string characters can compared. { if ( strncmp(&str[i],sub,strlen(sub)) == 0 ) { count++ ; } }
also, don't use gets
, prone buffer overflows. use fgets
instead.
Comments
Post a Comment