Q:

C program to remove a given word from the string

belongs to collection: C String Programs

0

C program to remove a given word from the string

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Read a string from the user then remove the given word from the string using C program.

Program:

The source code to remove a given word from the string is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to remove a given word from the string

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

int main()
{
    char str[64];
    char word[16];
    char words[6][16];

    int i = 0;
    int j = 0;
    int k = 0;
    int l1 = 0;
    int l2 = 0;

    printf("Enter string: ");
    scanf("%[^\n]s", str);

    printf("Enter word: ");
    scanf("%s", word);

    while (str[i] != 0) {
        if (str[i] == ' ') {
            words[k][j] = '\0';
            k++;
            j = 0;
        }
        else {
            words[k][j] = str[i];
            j++;
        }
        i++;
    }
    words[k][j] = '\0';

    j = 0;
    for (i = 0; i < k + 1; i++) {
        if (strcmp(words[i], word) == 0)
            words[i][j] = 0;
    }

    j = 0;
    printf("Result is:\n");
    for (i = 0; i < k + 1; i++) {
        if (words[i][j] == 0)
            continue;
        else
            printf("%s ", words[i]);
    }
    printf("\n");

    return 0;
}

Output:

RUN 1:
Enter string: Google Yahoo Bing
Enter word: Yahoo
Result is:
Google Bing 

RUN 2:
Enter string: Hello friends how are you?
Enter word: are
Result is:
Hello friends how you? 

RUN 3:
Enter string: is are am
Enter word: then
Result is:
is are am 

Explanation:

In the main() function, we created a string str and read the value of str and the word to be removed from the user. Then we removed the given word from the string and printed the result on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to delete duplicate words in the string... >>
<< C program to reverse every word of the given strin...