Find Occurrence of Substring in C using FunctionThis 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:
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
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. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India