C program to remove last occurrence of a word in string

Write a C program to remove from last occurrence of a word in given string using loop. How to remove the last occurrence of any word in given string using loop in C programming. Logic to remove last occurrence of a word from given string.

Required knowledge

Basic C programming, C if-else, C for loop, Array, functions, Strings

Logic to remove last occurrence of a word

  1. Input string from user, store it in some variable say str.
  2. Input word to be searched from user, store it in some other variable say word.
  3. Initialize a variable to store last matched index of word in given string, say index = -1. I have initially assumed that given word does not exists in string hence initialized with -1.
  4. Run a loop from start of the string str to end.
  5. Inside loop, for each character in word match the rest of characters with str. If all characters in word and str matches then, update index with current match position.
  6. Finally, after loop if index != -1 then, word has been found. Hence, shift all characters to left from the current index position.

Program to remove last occurrence of a word




  
/**
 * C program to remove last occurrence of a word in given string
 */
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
    char str[MAX_SIZE];
    char word[MAX_SIZE];
    int i, j, found, index;
    int stringLen, wordLen;


    /* Input string and word from user */
    printf("Enter any string: ");
    gets(str);
    printf("Enter word to remove: ");
    gets(word);

    stringLen = strlen(str);  // Length of string
    wordLen   = strlen(word); // Length of word


    /*
     * Run loop from start to end of string - word length
     */
    index = -1;
    for(i=0; i<stringLen - wordLen; i++)
    {
        // Match word at current position
        found = 1;
        for(j=0; j<wordLen; j++)
        {
            // If word is not matched
            if(str[i+j] != word[j])
            {
                found = 0;
                break;
            }
        }

        // If word is found then update index
        if(found == 1)
        {
            index = i;
        }
    }

    // If word not found
    if(index == -1)
    {
        printf("'%s' not found.");
    }
    else
    {
        /*
         * Shift all characters from right to left
         */
        for(i=index; i <= stringLen - wordLen; i++)
        {
            str[i] = str[i + wordLen];
        }

        printf("String after removing last '%s': \n%s", word, str);
    }

    return 0;
}



Output:

Enter any string: i love c programming
Enter string to be removed: ming
String after removing 'ming':
i love c program
Process returned 0 (0x0) execution time : 21.655 s



Instagram