Example:
Input string: I love programming. I love CodeforWin.
Input word to search: love
Output total occurrences of 'love': 2
Required knowledge
Basic C programming, Loop, String, FunctionBefore counting total occurrences of a given word in a string you must know the basics of how to count total occurrences of a character in given string.
Program to count occurrences of a word
/**
* C program to count occurrences of a word in a given string
*/
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 //Maximum size of string
/* Function declaration */
int countOccurrences(char * string, char * toSearch);
int main()
{
char string[MAX_SIZE];
char toSearch[MAX_SIZE];
int occurrences;
/*
* Reads string and word to be searched from user
*/
printf("Enter any string: ");
gets(string);
printf("Enter word to search occurrences: ");
gets(toSearch);
occurrences = countOccurrences(string, toSearch);
printf("Total occurrences of '%s': %d\n", toSearch, occurrences);
return 0;
}
/**
* Gets, the total number of occurrences of a word in a string
*/
int countOccurrences(char * string, char * toSearch)
{
int i, j, found, occurrences;
int stringLen, searchLen;
stringLen = strlen(string); //Gets, length of string
searchLen = strlen(toSearch); //Gets, length of word to be searched
occurrences = 0;
for(i=0; i<=stringLen - searchLen; i++)
{
/*
* Matches the word with string
*/
found = 1;
for(j=0; j<searchLen; j++)
{
if(string[i+j] != toSearch[j])
{
found = 0;
break;
}
}
if(found == 1)
{
occurrences++;
}
}
return occurrences;
}
Output
Enter any string: I love programming. I love CodeforWin.
Enter word to search occurrences: love
Total occurrences of 'love': 2
Enter word to search occurrences: love
Total occurrences of 'love': 2
Happy coding ;)
You may also like
- String programming exercises index.
- C program to find first occurrence of a word in a string.
- C program to find last occurrence of a word in a string.
- C program to search all occurrences of a word in a string.
- C program to remove first occurrence of a word from a string.
- C program to remove last occurrence of a word from a string.
- C program to remove all occurrences of a word from a string.
- C program to compare two strings.
- C program to reverse any string.