Find Last Occurrence of substring in string in C

Program-Find-Last-Occurrence-of-substring-in-string-in-C-programming-language

Program Description:

Write a Program to find last occurrence 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 must then look for the last occurrence of the substring within the main string and return the index of the last occurrence.

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

We are going to look at a few methods to find the last 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.

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

Here is the example input and output of the program.

Expected Input and Output:

Input:

Enter a main string : go go go go go lewis

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

Output:

FOUND! Last Occurrence of Substring:'go' is found at 12 index in Main String

The last occurrence of the substring go is found in the main string.

Prerequisites:

It is recommended to know the basic of the C-Strings, C-Arrays, and Functions in C to better understand the following program.

We will look at two methods to search for the substring in the main string. They are

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

Let’s look at the step-by-step explanation for the iterative program.

Algorithm to Find Last Occurrence of substring in string in C (Manual Method):

  1. 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.
  2. Take two strings from the user and store them in mainStr and subStr respectively. We use the gets function to read the strings.
  3. Initialize a variable called lastStrIdx with the value -1. This variable is used to track the index of the last occurrence of the substring in the main string.
  4. To search for the last occurrence 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.
  5. 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. So update the lastStrIdxvariable with the current index( i). – i.e lastStrIdx = i;
    • Continue to the next iteration to search for remaining occurrences of the substring ( subStr).
  6. 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.
    • If the lastStrIdxis updated, Then we found the substring in the main string and the last occurrence of the substring is updated in the lastStrIdx variable.
    • Display the results based on the above value.
  7. Stop the program.

Find Last Occurrence of substring in string in C – Iterative Method:

Here is the program to find the last occurrences of a substring in a main string in C programming language.

Include the string.h header file to access the strlen() function.

Program Output:

Let’s Compile and Run the Program.

Test Case 1: Positive Cases:

search-for-last-occurrence-of-substring-in-a-string-program-output

In the above example, The last occurrence of the substring very is found at the 22nd index in the main string. i.e Internet is very very very fast

Let’s look at another example.

As we can see the go substring is found in the main string and the program proerply returned the last occurrence index.

Test case 2: Negative Case:

In this case, The substring max is not found in the main string Will george be world champion?

Program to Find Last Occurrence of a substring in string using a user-defined function:

In this method, Let’s utilize the C functions to divide the above program into sub-sections. So let’s create a function to find the last occurrence of the substring in the main 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 Advantages of the functions in programming.

The Modified program finds the index of the last occurrence of a substring in the string using a user-defined function.

We have defined a function named getLastSubStr() function in the above program. This function is used to find the index of the last occurrence of the substring in the main string. Here is the prototype of the function.

The getLastSubStr function takes two character pointers( char *) as the formal arguments. They are mainStr and subStr respectively. It searches for the occurrences of the subStr in the mainStr

This function also returns a Integer value( int) back to the caller. If the subStr is found in the mainStr, It returns the index of the last occurrence of subStr, If the subStr is not found int he mainStr, It returns -1.

In the main() function, Call the getLastSubStr() function with the two strings ( mainStr and subStr) and capture the return value in a variable.

Finally, display the results on the console based on the return value of the function.

Program Output:

Compile and Run the program using GCC compiler (Any compiler)

prorgram-search-for-last-occurrence-of-substring-in-a-string-using-functions

As we can see from the above output, The substring lorry is found multiple times in the main string red lorry yellow lorry. The getLastSubStr function properly calculated the last occurrence index and returned to the main() function.

Similar String Programs:

Venkatesh

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...

1 Response

  1. […] C Program to Find Last Occurrence of Substring/Word in a String […]

Leave a Reply