×

Find occurrence of substring in C using function

Introduction: In this article, we discuss finding the occurrence of a substring in C using function. This software takes strings and substrings as input and counts the occurrences of substrings within strings. Next, we'll look at how to find the number of occurrences of a substring in a string. The C string library () provides a function (strstr()) that checks for the existence of substrings. But I don't know how often the substring is inside the string. Implement your function with or without the strstr() function.

Now we provide a few examples of the occurrence of a substring in C and the use of the function. Here is the solution:

  1. At first, it takes strings and substrings as input.
  2. Then, first look for a substring within the string.
  3. After that, count the instances that exist, if any. 

The following is the supply code for a C program that counts the wide variety of occurrences of a substring in a string. The C software builds and runs quality on my Linux gadget. Below is also the output of the utility.

Example 1: Here, we give an example of finding the occurrence of substring in C using function. The example is given below –

# include < stdio.h >  
# include < string.h >  
# include < stdlib.h >  
# include < conio.h >  
int substring_count (char * string, char * substring) 
{  
int i, j, S1, S2;  
int count = 0;  
 S1 = strlen (string);  
S2 = strlen (substring);  
for ( i = 0 ; i < S1 - S2 + 1 ; i + + ) 
{  
if (strstr( string + i , substring ) = = string + i ) 
{  
count + +;  
i = i + S2 - 1;  
}  
}  
return count;  
}  

Output: Now we compile the above program and also run it. After running this program, the output is given below –

Enter a string: If life were predictable, it would cease to be life and be without flavor.
Enter substring: he
Substring occurrence count is: 2

Explanation of the above program: Instead of creating my inner loop, I used the strstr() method to determine if a substring matched a specific position in the outer loop. A pointer to the first matching character is returned from the strstr() method. A counter is incremented when the pointer equals the outer loop start character pointer.

You can use the strcmp() method to achieve the same goal. The strrchr function returns the last character found in a string. Returns a NULL pointer instead of a character pointer if the character is not recognized.

Let's write a program that uses these functions to print each lowercase letter's first and last index in a string. Both strchr and strchr return a pointer to the character for which occurrences of the desired characteristics are recognized.

Let's say the character to search for is 'b', and the string to search for is 'abcd'. A pointer to the character "b" in the string is then returned. A null is returned if the surface is missing.

Example 2: Here, we give another example of finding the occurrence of substring in C using function. The example is given below –

# include < stdio.h >  
# include < string.h >  
# include < stdlib.h >  
# include < conio.h >  
char str [100], sub [100];  
int count = 0, count1 = 0;  
void main ()  
{  
 int i, j, l, l1, l2;  
 printf (" \ n Enter a string: ");  
 scanf (" % [^ \ n] s ", str );  
  l1 = strlen (str);  
 printf (" \ n Enter a substring: ");  
 scanf (" % [^ \ n] s ", sub);  
 l2 = strlen (sub);  
for ( i = 0 ; i < l1 ; i++ )  
 {  
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);
return 0;  
}  

Output: Now we compile the above program and also run it. After running this program, the result is given below –

Enter a string: progggram c progggramming
Enter a substring: gg
gg occurs two times in progggram c progggramming

Explanation of the above program: It takes strings and substrings as input and places them in the best str and sub fields. Use the strlen function to determine the length of each string. Use a for loop to determine if a substring exists. In this example, we use the matter variable to be counted the range of occurrences. Offers several variables as output.

 So, in this program, we briefly discuss how to find the occurrence of substring in C using function. We give some examples and share the output of these programs. 


Related Topics

String literals in C

Constants refer to the fixed values of the program that may not alter during the compiling ad execution. These fixed values are known as literals. In other words, the values...

3 minutes read.

Bit Fields in C

The size of a structure in C is specified in bits. The primary goal of it is to use memory efficiently, once we understand that a bit's value must fall...

3 minutes read.

Bank management system in C

This is a mini project that is constructed completely using the C language. The bank management system is a beginner friendly project. To construct this user only needs to know...

12 minutes read.

Banker’s Algorithm in C

Introduction Before doing a "s-state" check to look for potential activities and deciding if allocation should be allowed to continue, the banker's algorithm, a resource allocation and deadlock avoidance algorithm, tests...

5 minutes read.

Floyd’s triangle in C

Floyd’s triangle in C Floyd’s triangle is named after a person Robert Floyd. It is a right-angled triangle that is of natural numbers starting from 1 and consecutively selects the upcoming...

4 minutes read.

Escape Sequence in C

An escape sequence is a sequence of character that used inside the string literal or character.  All the escape sequence is used with the backslash (\) symbol. The list of an...

1 minute read.

Decimal to Binary in C

What is a decimal number? A decimal number is a number represented in the decimal number system. This system of binary conversion uses base 10 to represent numbers, i.e. the digits...

3 minutes read.

Add two numbers using the function in C

Here we will learn how to add two numbers by creating function in C. Let’s learn this with help of example. Code: - #include <stdio.h> int add_two_no(int a, int b); int main(){   int first_num,...

1 minute read.

#undef in C

#undef in C In the C programming language, the #undef directive is used to undefine the macro or any constant, which will be defined by the preprocessor directive #define. The #undef...

3 minutes read.

Type Casting in C

Type casting is a way to convert a variable from one data type to another data type.Syntax: (type) expression;     Example: #include <stdio.h> int main() { int a,b; float sum; printf("Example of Type Casting\n"); printf("Enter any integer nos:"); scanf("%d",&a,&b); sum=a+b; printf("Sum: %f",sum); return 0; } Output Example...

1 minute read.

Run Time Polymorphism in C

What is polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. An individual who can have...

4 minutes read.

C vs Java Strings

String in C In C, we can define a string as a bunch of characters. A character array is distinguished from a string by the presence of the special character '\0'...

5 minutes read.

Queue implementation in C

In the C programming language, the queue is the abstract concept that is similar to stacks. However, it is the part of the data structures that work opposite to that...

4 minutes read.

Types of Pointers in C

Pointers in C A pointer is a variable and this variable contains the address of another variable, i.e it’s a variable which has the address of another variable as its value....

4 minutes read.

Reverse a Stack using Recursion in C

In this tutorial we will learn how recursion will be used in this case to reverse a stack. For loops, while loops, do-while loops, and similar constructions are not permitted....

5 minutes read.

Derived Data Types in C

A variable in a program occupies some space in the computer's memory where some value is stored. Each variable in C has an associated data type. A value to be...

4 minutes read.

How to get ASCII value in C

For text data on computers and the internet, ASCII (American Standard Code for Information Interchange). It is the most widely used character encoding standard. One hundred twenty-eight alphabetic, numeric, special...

3 minutes read.

Git Hooks

Git Hooks Overview Just like other version control systems, Git has its way to deliver customized scripts whenever some important activity occurs. The hooks act just like the triggers or catalysts...

4 minutes read.

SJF Scheduling Program in C

The SJF (shortest job first) or the shortest job next is the programming scheduling in the C. It is one of the CPU scheduling programming. The SJF is defined as...

4 minutes read.

Float in islower() in C

Introduction: This article briefly discusses the float in islower() in C. The islower() function checks if the input character passed inside the function is lowercase. Lowercase letters include (a-z). The islower()...

4 minutes read.