Find All Occurrences of substring in string in C Program

Spread the love
Find-All-Occurrences-of-substring-in-string-in-C-Program

Program Description:

Write a Program to Find All Occurrences of substring in string in C Programming language. The program should accept two strings from the user, one for the main string and one for the substring. The program needs to find all occurrences of the substring within the main string.

We are going to look at a couple of methods to find all occurrences of substring and each program will be followed by a detailed step-by-step explanation of the program and program output. We also included the instructions to compile and run the program.

📢 This Program is part of the C String Practice Programs series

Input and Output:

Input:

Enter a main string : music is bliss and music is soothing

Enter the substring(String to search in main string): music

Output:

FOUND! The Substring:'music' is found at 0 index

FOUND! The Substring:'music' is found at 19 index

If you observe the above output, The substring music is found in two places in the main string.

📢 The program is case-sensitive. As a result, upper-case characters will differ from lower-case characters.

Prerequisites of the program:

It is recommended to go through the following articles to better understand the program.

We will look at two methods to find all occurrences of the substring in the main string. They are

  • Manual Approach(Iterative) – Where we use an iterative method to find the sub-string in the main string
  • User-defined function – We use a custom user-defined to find all occurrences of the target string in the main string.

Find All Occurrences of substring in string in C Program Explanation:

Let’s look at the instructions to find all occurrences of a string in a string.

  1. Create a Macro called SIZE with the value 100. The SIZE holds the max size of the strings. please change this if you want to use large strings.
  2. Start the main() function by declaring the two strings and naming them as mainStr and subStr. The size of both strings is equal to SIZE macro.
  3. Initialize a variable called isFound with the value -1. This variable is used verify if we found the sub string( subStr) in the main string( mainStr).
  4. Take two strings from the user and store them in mainStr and subStr respectively. We use the gets function to read the strings.
  5. To find all occurrences of substring( subStr) in the main string( mainStr), Iterate through the main string( mainStr), looking for the first character of the substring( subStr[0]). If we found the first character of the substring, we should then determine whether all other characters of the substring match. If that’s the case, we found the substring( subStr) in the main string( mainStr). Similar way we need to look for all occurrences of the substring.
  6. Create a For loop by initializing variable i with 0 to iterate over the mainStr. It will continue looping as long as the current character ( mainStr[i]) is not a NULL character ( '\0').
    • At each iteration, Check if the current character( mainStr[i]) is equal to the first character of the substring( subStr[0]) - i.e if(mainStr[i] == subStr[0])
    • If the above condition is true, Then search for all characters of the subStr in the mainStr. We need to use another for loop to iterate over the contents of the subStr – i.e for(j=0; subStr[j]; j++).
      • Check if the mainStr[k] (where k = i) is not matching to subStr[j], If so then the subString is not found. Otherwise, continue to check all elements of the subStr.
    • Once the above loop is completed, Check if we iterated complete subStr ( use j == strlen(substr) ). If we iterated the complete substring( subStr), then we found the match and print the index on the screen. So update the isFoundvariable with the current index( i). – i.e lastStrIdx = i;
    • Continue to the next iteration to search for remaining occurrences of the substring ( subStr).
  7. If step 5 is completed, Check the value of the lastStrIdx variable.
    • If it is equal to the -1, Then we haven’t found the substring( str) in the main string( mainStr). Display the NOT FOUND message on the console.
  8. Stop the program.

Program to Find All Occurrences of substring in string in C – Iterative Method:

Here is the program to find all occurrences of substring in the main string in c programming language using loops.

As we are using the strlen() library function, We need to include the string.h header file.

Program Output:

Compile the program using the following command.

$ gcc search-str-all.c

Run the executable file. ( i.e a.out is our executable file name)

Example 1:

Find-All-Occurrences-of-sub-string-in-a-string-in-c-program-output

In the above example, The main string is music is bliss and music is soothing and the substring is music. The program is able to find all occurrences of the music in the main string and displayed the indices of the substring.

Example 2:

In this example, The substring sad is not present in the main string Happy and Cheerful.

Find All Occurrences of substring in string using a user-defined function in C:

In the above method, We have written the complete program inside the main() function. Let’s rewrite the above program to use a function to find all occurrences of a sub string in a string.

By using the functions we can define a function once and can call it as many times as we want. Functions also increase the readability of the program and make it easier to debug issues. Here are the benefits using the functions in programming.

In the following program, We have defined a function called printAllSubStr() to find and print indices of all occurrences of the given substring in the main string.

The prototype of the printAllSubStr() function is – int printAllSubStr(char *mainStr, char * subStr)

As we can see, It takes two formal arguments, They are mainStr and subStr. Both these arguments are character pointers pointing to the main string and substring respectively.

This function searches for the subStr in the mainStr and prints the indices of the subStr. The return value of the function is Integer ( int). It returns > 0 if the subStr is found in the mainStr, otherwise, it returns -1.

Call the printAllSubStr() function from the main() function with mainStr and subStr as arguments.

The isFound variable contains the return value of the function.

Program Output:

Let’s compile and run the program.

Example 1:

The substring day found two times in the main string at the index 7 and 34.

Example 2:

Find-All-Occurrences-of-sub-string-in-a-string-using-function

The string language is not found in the main string Learn Programming.

As we can see from the above outputs, The program is properly finding the all occurrences of the substring in the main string.

More String Programs:

Venkat

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

Leave a Reply