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.

Example:
Input string : I love to code.
Input word to remove : to
Output : I love code.

Required knowledge:

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

Before continuing to this program you must know how to find the first occurrence of a word in the given string.

Program:

/**
 * C program to remove the first occurrence of a word in a string
 */

#include <stdio.h>
#include <string.h>

#define MAX_SIZE 100


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


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

    /*
     * Reads a string from user and character to be searched
     */
    printf("Enter any string: ");
    gets(text);
    printf("Enter string to be removed: ");
    gets(toRemove);

    removeFirst(text, toRemove);

    printf("\nFinal string after removing '%s' = %s", toRemove, text);

    return 0;
}


/**
 * Removes the first occurrence of a string in another string
 */
void removeFirst(char * text, const char * toRemove)
{
    int i, j;
    int len, removeLen;
    int found = 0;

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

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

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

            text[j] = '\0';

            break;
        }
    }
} 


Output
Enter any string: I write code.
Enter string to be removed: write

Final string after removing 'write' = I  code.

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