C program to remove first occurrence of a word from string

Write a C program to input any string from user and remove first occurrence of a given word from string. Write a function to remove first occurrence of a word from the string. How to remove first occurrence of a word from the string in C programming. Logic to remove first occurrence of a word from given string.

Example

Input

Input string : Learn programming at Codeforwin.
Input word to remove : Learn

Output

String after removing 'Learn': 
programming at Codeforwin.

Required knowledge

Basic C programming, If else, Loop, Array, String

Must know – Program to search first occurrence of a word

Logic to remove first occurrence of a word

Below is the step by step descriptive logic to remove first occurrence of a word in given string.

  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. Run a loop from start of the string str to end.
  4. Inside loop, for each character in word match rest of characters with str. If all characters in word matched to str, then proceed to next step.
  5. If a word match is found then, shift all characters from current match position to left.

Program to remove first occurrence of a word in given string

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

/** Function declaration */
void removeFirst(char * str, const char * toRemove);


int main()
{
    char str[MAX_SIZE];
    char toRemove[MAX_SIZE];

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

    removeFirst(str, toRemove);

    printf("\nString after removing '%s': \n%s", toRemove, str);

    return 0;
}


/**
 * Remove first occurrence of a word from string
 */
void removeFirst(char * str, const char * toRemove)
{
    int i, j;
    int len, removeLen;
    int found = 0;

    len = strlen(str);
    removeLen = strlen(toRemove);

    for(i=0; i<len; i++)
    {
        found = 1;
        for(j=0; j<removeLen; j++)
        {
            if(str[i+j] != toRemove[j])
            {
                found = 0;
                break;
            }
        }

        /* If word has been found then remove it by shifting characters  */
        if(found == 1)
        {
            for(j=i; j<=len-removeLen; j++)
            {
                str[j] = str[j + removeLen];
            }

            // Terminate from loop so only first occurrence is removed
            break;
        }
    }
}

Output

Enter any string: Learn programming at Codeforwin.
Enter string to be removed: Learn

String after removing 'Learn':
programming at Codeforwin.

Happy coding 😉