Advertisement
defineSN

count num of a string within another string

Feb 3rd, 2013
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.44 KB | None | 0 0
  1. /*count string within another string*/
  2. #include<stdio.h>
  3. #include<string.h>
  4. #include<stdlib.h>
  5.  
  6. void remLin(char *);
  7.  
  8. int main(){
  9.    
  10.     int index,checker,count=0,ls1,ls2;
  11.     char *s1,*s2;
  12.    
  13.     printf("enter max length of s1:");
  14.     scanf("%d",&ls1);
  15.     printf("enter max length of s2:");
  16.     scanf("%d",&ls2);
  17.    
  18.     while((getchar())!='\n'){}
  19.    
  20.     printf("\nenter s1: ");
  21.     fgets( (s1=(char*)malloc(sizeof(char)*ls1)) , ls1 , stdin);
  22.     remLin(s1);
  23.    
  24.     printf("\nenter s2: ");
  25.     fgets( (s2=(char*)malloc(sizeof(char)*ls2)) , ls2 , stdin);
  26.     remLin(s2);
  27.    
  28.     for(index=0,checker=0;s1[index]!='\0';index++){
  29.        
  30.         printf("\n\n at for() start>> location: %3d  s1 contains: %3c  count value: %3d",index,s1[index],count);
  31.        
  32.         while((s1[index]==s2[checker]) && ((s1[index])!='\0') && ((s2[checker])!='\0')){
  33.             checker++;
  34.             index++;       
  35.         }
  36.        
  37.         if(checker>0)
  38.             index=index-1; // this compensates for one extra index increment at the end of while()
  39.        
  40.         if(checker==(strlen(s2))){
  41.             count++;       
  42.            
  43.         }
  44.         checker=0;
  45.        
  46.         printf("\n at for()   end>> location: %3d  s1 contains: %3c  count value: %3d",index,s1[index],count);
  47.     }
  48.    
  49.     printf("\n\ncount of %s in %s is: %d\n\n",s2,s1,count);
  50.    
  51.    
  52.     return 0;
  53. }
  54.  
  55. void remLin(char *str){
  56.     int len=strlen(str);
  57.     if(str[len-1]=='\n')
  58.         str[len-1]='\0';
  59.     realloc(str,len); // trims up the string
  60.     printf("\nentered string: %s and its length: %d\n\n",str,strlen(str)); // strlen will not count the null terminator
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement