Javatpoint Logo
Javatpoint Logo

Find Occurrence of Substring in C using Function

This software counts the number of times a substring appears in a string after receiving a string and a substring as input. Let us look at an example:

Solution would be:

  • Take as input a string and a substring.
  • Look first in the string for the substring.
  • Count the instances where it is present if it is there.

Here is the C program's source code for counting the occurrences of a substring within a string. On a Linux machine, the C program is successfully built and executed. Also given below is the output of the application.

Example:

Output:

enter a string : prrrogram c prrrogramming
enter a substring : rr
rr occurs 2 times in prrrogram c prrrogramming
..............................................
Process executed in 2.22 seconds
Press any key to continue.

Explanation

  • Take a string and a substring as input and place them in the corresponding str and sub fields.
  • Use the strlen function to determine the length of both strings.
  • Determine if a substring is present or not using a for loop. If so, use the count variable to count how many times it is present.
  • Print the number of variables as output.

Using Function:

Output:

enter a string : If life were predictable it would cease to be life and be without flavor
enter substring : be
Substring occurrence count is : 2
..............................................
Process executed in 1.22 seconds
Press any key to continue.

Explanation

We utilized the strstr() method rather than creating our own inner loop to determine whether the substring matches from a certain location in the outer loop. The first matching character's pointer is returned by the strstr() method. The counter is increased if the pointer is equal to the pointer for the outer loop's initial character. With the help of the strcmp() method, we can accomplish the same goal. The strchr function gives the string's first instance of each character.

The strrchr function returns the character that last appeared in a string. If the character is not detected, they return a NULL pointer instead of a character pointer. Let's create a program that outputs the first and last index of every lower-case character in a string using these functions.

A pointer to the character where the occurrence of the desired character is detected is returned by both strchr and strrchr. Let's say the character to be searched for is "b" and the string to be searched is "abcd." A pointer to character "b" in the string is then given back. In the absence of the character, NULL is returned.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA