Sunday, July 12, 2009

Help with c programming?

I am working on a program that i need the user to input two lines of text. The first longer then the second. The program is supposed to count how many times the second line appears in the first line. I am almost done. I am having trouble testing if line 2 is in line1 because it must be case and space sensitive . if anyone has examples or any suggestions i would appreciate it. thnx





int strstrcnt(const char *s1, const char *s2, int j)


{


int count;


char * strstr(const char *s1, const char *s2);


char *k;


/*for(j=0; j%26lt;s1size; j++)*/





k = strstr(s1,s2), count++;











return(k);


}





This is a sample of my code can anyone help. I have the part where the program asks the user i just need help with this function to count the number of occurrences. thnx

Help with c programming?
As you realise, the strstr() function is the right choice. You need to test the return value from strstr() and if not null, increase your counter, and test for another occurance of the smaller string until it does not find one.





The trick to use a pointer that initially points to the start of the large string, and is bumpped up for each successive call.





Something like this should be close to what you need.





int count( char *large, char *small )


{


char *cp; /* pointer at what to give to strstr */


char *nxt; /* pointer at next occurance of little */


int slen; /* length of little string */


int count = 0;





slen = strlen( small );


cp = large;


while( strlen(cp) %26gt; slen %26amp;%26amp; (nxt = strstr( cp, small )) != NULL )


{


count++;


cp = nxt + slen; /* skip over last match */


}





return count;


}
Reply:Instead of coding it for you, I'll suggest an approach.





L1 = length(s1);


L2 = length(s2);


for (i = 0; i %26lt; ((L1 - L2); i++)


create s3, which is length L2, starting from s1[i]


compare and count


No comments:

Post a Comment