20/03/2016

C Program to Delete a Substring From a String [Updated]

Write a C Program to Delete a Substring From a String or how to remove a word from a string or c program to delete a word from a string. In this program, we have to remove a particular word or substring from a sentence or string. So first we have to take a string and store in a variable after that we have to enter the word or substring which user want to remove from the original string or sentence.

Below we have explained everything about the program to remove substring from a string, Deleting Substring in C is not very hard it's very simple so don't worry about the solution.

C Program to Delete a Substring From a String


Explanation How to Remove a Word from a String


C Program to Delete a Substring From a String: Just like a searching an element in a sentence or in the string we have to perform the same operation to delete the particular word in a string or sentence. After that, we have to first find the word is present in the string on sentence after that remove the word from the string or sentence.

C Program to Delete a Word from a String: So first run a loop for the main string and compare the string to substring, for each iteration increase the value of the index if the substring is matched with the main string. Then remove or if you want to print only the output so you can skip the character from main strings.

C Program to Delete a Substring From a String


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

int main()
{
    int i, j = 0, k = 0,n = 0;
    int flag = 0;
 
    char str[100], neww[100], word[100];

    printf("Enter Any String to Remove a Word from String: ");
    gets(str);

    printf("\n\n Enter Any Word You Want to be Removed: ");
    gets(word);

    for(i = 0 ; str[i] != '\0' ; i++)
    {
        k = i;
     
        while(str[i] == word[j])
        {
            i++,j++;
            if(j == strlen(word))
            {
                flag = 1;
                break;
            }
        }
    j = 0;

    if(flag == 0)
        i = k;      
    else
        flag = 0;

    neww[n++] = str[i];
    }

    neww[n] = '\0';
    
    printf("\n\n After Removing Word From String: %s",neww);
}

Delete a Substring From a String Program Output


Delete a Substring From a String Program Output

Similar to C Program to Delete a Word from a String

Previous Post
Next Post

post written by:

Hi, I’m Ghanendra Yadav, SEO Expert, Professional Blogger, Programmer, and UI Developer. Get a Solution of More Than 500+ Programming Problems, and Practice All Programs in C, C++, and Java Languages. Get a Competitive Website Solution also Ie. Hackerrank Solutions and Geeksforgeeks Solutions. If You Are Interested to Learn a C Programming Language and You Don't Have Experience in Any Programming, You Should Start with a C Programming Language, Read: List of Format Specifiers in C.
Follow Me

0 Comments: