this is an exam question i failed to answer properly, im trying to work it out. the code i came up with is below, it works ok, but i was hoping if anyone could help in improving it. iv read in various threads in daniweb itself about making a code run faster etc.. havent really understood much, maybe anyone can help me understand them here, with this code if possible. thanks a lot in advance :)
#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
}
somjit.
ps: pardon a few obvious comment lines, i just kept them there so that i can understand what i did later on. :)