This is a C Program to count the occurrence of a substring in string.
This program takes a string and a substring as input and counts the occurrence of a substring in string.
1. Take a string and a substring as input.
2. Firstly check for the substring in the string.
3. If it is present then count the number of times it is present.
Here is source code of the C Program to count occurrence of a substring in string. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program To Count the Occurrence of a Substring in String
*/
#include <stdio.h>
#include <string.h>
char str[100], sub[100];
int count = 0, count1 = 0;
void main()
{
int i, j, l, l1, l2;
printf("\nEnter a string : ");
scanf("%[^\n]s", str);
l1 = strlen(str);
printf("\nEnter a substring : ");
scanf(" %[^\n]s", sub);
l2 = strlen(sub);
for (i = 0; i < l1;)
{
j = 0;
count = 0;
while ((str[i] == sub[j]))
{
count++;
i++;
j++;
}
if (count == l2)
{
count1++;
count = 0;
}
else
i++;
}
printf("%s occurs %d times in %s", sub, count1, str);
}
1. Take a string and a substring as input and store it in the array str and sub respectively.
2. Find the length of both the strings using strlen function.
3. Using for loop find whether the substring is present or not. If it is present then count the number of times it is present using the variable count.
4. Print the variable count as output.
Enter a string : prrrogram c prrrogramming Enter a substring : rr rr occurs 2 times in prrrogram c prrrogramming
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship
- Check C Books
- Apply for C Internship
- Practice BCA MCQs