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. Removing last occurrence of a given word in a string using loop in C program.

Example:
Input string: I am a programmer. I love CodeforWin
Input word to remove: I
Output: I am a programmer. love CodeforWin

Required knowledge

Basic C programming, Loop, String

Before moving on to this program you must be done with two programs - C program to remove last occurrence of a character and C program to find last occurrence of word in given string. As logic of this program is based on these two programs.

Program to remove last occurrence of word

/**
 * C program to remove last occurrence of a word in given string
 */

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 //Maximum size of string

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


    /*
     * Reads string and word from user
     */
    printf("Enter any string: ");
    gets(string);
    printf("Enter any word to search: ");
    gets(word);

    stringLen = strlen(string); //Finds length of string
    wordLen = strlen(word); //Finds length of word


    /*
     * Runs a loop from starting index of string to
     * length of string - word length
     */
    index = -1;
    for(i=0; i<stringLen - wordLen; i++)
    {
        //Matches the word at current position
        found = 1;
        for(j=0; j<wordLen; j++)
        {
            //If word is not matched
            if(string[i+j] != word[j])
            {
                found = 0;
                break;
            }
        }

        //If word have been found then store the current found index
        if(found == 1)
        {
            index = i;
        }
    }

    //If word not found
    if(index == -1)
    {
        printf("'%s' not found.\n");
    }
    else
    {
        /*
         * Shifts all characters from right to left
         */
        for(i=index; i<stringLen - wordLen; i++)
        {
            string[i] = string[i + wordLen];
        }
        //Makes last character null.
        string[i] = '\0';

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

    return 0;
}


Output
Enter any string: I love programming. I love CodeforWin.
Enter any word to search: I
String after removing last 'I': I love programming. love CodeforWin.

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment