Function to find Occurrences

Write a function Occurrences() in a language of your choice that takes in two strings. The first is a search string, and the second is a sentence. For example, running the function:

Running Occurrences ("o", "Red Gate Software - Ingeniously Simple Tools")

will output: Occurrences of 'o': 4

Occurrences ("at", "The cat sat on the mat")

will output: Occurrences of 'at': 3

charles.

Questions by prissicharles

Showing Answers 1 - 2 of 2 Answers

the_code

  • Aug 24th, 2011
 

Below is the code to do this in C language. Hope this helps.

Code
  1. #include<stdio.h>

  2. #include<string.h>

  3.  

  4. int count_occurences(char *big, char *small)

  5. {

  6.         char *temp;

  7.         int count=0;

  8.         temp=strstr(big,small);

  9.         while (temp!=NULL)

  10.         {

  11.     temp=strstr(temp+1,small);

  12.     count++;

  13.         }

  14.         return (count);

  15. }

  16. int main()

  17. {

  18.         char big_string[]="The fat cat sat on a mat",search_string[]="at";

  19.         printf("total %d occurences found

  20. ",count_occurences(big_string,search_string));

  21.         return 0;

  22. }

  23.  

  24.  

  Was this answer useful?  Yes

shashank

  • Nov 3rd, 2011
 

Code
  1. void occ(char *x,char *y)

  2. {

  3.  char *a;

  4.  int r=0;

  5.  

  6.  while(a=strstr(y,x))

  7. {

  8.   r+=1;

  9.   y=a+1;

  10. }

  11. return r;

  12. }

  13.  

  14. void main()

  15. {

  16.  printf("occurances = %d",occ("at","the cat sat on the mat"));

  17. }

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions