Rahul Mayuranath
Rahul Mayuranath

Reputation: 29

Find number of sub strings in a string

The below code produces a ridiculous output of 32674 for a test input of counting number of 'aa' in 'aaa'. How do i go about correcting this?

#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") ; 
    fgets(str,sizeof(str),stdin) ;
    printf("Enter the substring to be searched for") ;
    fgets(sub,sizeof(str),stdin) ;
    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] ;
           }          
           comp[k+1]='\0' ; 
          /*A previous suggestion given : comp[k]    
          to be the null character but I dont see how/why? and that is   
          giving a similarly wrong output as well. */
         if ( strcmp(comp,sub) == 0 )
            { count++ ; }
     }
    printf("no of occurances is:%d",count) ;
    return 0 ;
} 

Upvotes: 0

Views: 65

Answers (2)

chux
chux

Reputation: 153517

count is not initialized, so the printed value of count is not useful.

int i,j,len ,k ,count, num ;
count = 0; // add
...
{ count++ ; }
...
printf("no of occurances is:%d",count) ;

Suggest removing a potential \n from the end of input.

fgets(str, sizeof str ,stdin);
str[strcspn(str, "\n")] = '\0'; // add

Other issues may exist: @dbush

Upvotes: 2

dbush
dbush

Reputation: 224002

Two issues:

fgets reads a newline and adds it to the string that is read in. You need to remove it:

if (str[strlen(str)-1] == '\n') str[strlen(str)-1]='\0';
...
if (sub[strlen(sub)-1] == '\n') sub[strlen(sub)-1]='\0';

When building the substring to compare, you're putting the null terminator one space too far:

comp[k+1]='\0' ;

k was already incremented before the loop exits, so no need to add 1:

comp[k]='\0' ;

Upvotes: 1

Related Questions