Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*count string within another string*/
- #include<stdio.h>
- #include<string.h>
- #include<stdlib.h>
- void remLin(char *);
- int main(){
- int index,checker,count=0,ls1,ls2;
- char *s1,*s2;
- printf("enter max length of s1:");
- scanf("%d",&ls1);
- printf("enter max length of s2:");
- scanf("%d",&ls2);
- while((getchar())!='\n'){}
- printf("\nenter s1: ");
- fgets( (s1=(char*)malloc(sizeof(char)*ls1)) , ls1 , stdin);
- remLin(s1);
- printf("\nenter s2: ");
- fgets( (s2=(char*)malloc(sizeof(char)*ls2)) , ls2 , stdin);
- remLin(s2);
- for(index=0,checker=0;s1[index]!='\0';index++){
- printf("\n\n at for() start>> location: %3d s1 contains: %3c count value: %3d",index,s1[index],count);
- while((s1[index]==s2[checker]) && ((s1[index])!='\0') && ((s2[checker])!='\0')){
- checker++;
- index++;
- }
- if(checker>0)
- index=index-1; // this compensates for one extra index increment at the end of while()
- if(checker==(strlen(s2))){
- count++;
- }
- checker=0;
- printf("\n at for() end>> location: %3d s1 contains: %3c count value: %3d",index,s1[index],count);
- }
- printf("\n\ncount of %s in %s is: %d\n\n",s2,s1,count);
- return 0;
- }
- void remLin(char *str){
- int len=strlen(str);
- if(str[len-1]=='\n')
- str[len-1]='\0';
- realloc(str,len); // trims up the string
- printf("\nentered string: %s and its length: %d\n\n",str,strlen(str)); // strlen will not count the null terminator
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement