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.

Required knowledge

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

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: I love programming coding
Enter string to be removed: ming
String after removing 'ming':
I love program coding
Process returned 0 (0x0) execution time : 29.055 s



Instagram