codescracker


c++

C++ Program to Delete Words from Sentence



« Previous Program Next Program »


Delete Words from Sentence in C++

To delete particular words from the string or sentence in C++ programming, you have to ask to the user to enter the string or sentence, and then ask to enter the word to delete all the given/entered word from the sentence and then display the new sentence after deleting all the desired word from the sentence as shown here in the following program.

C++ Programming Code to Delete Words from Sentence

Following C++ program ask to the user to enter a sentence then ask to enter a word to be delete from the sentence, then display the new sentence after deleting the given word:

/* C++ Program - Delete Words from Sentence */
		
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
    clrscr();
    int i, j = 0, k = 0, count = 0;
    char str[100], str1[10][20], word[20];
    cout<<"Enter the String : ";
    gets(str);

    /* Converting the string into 2D Array */

    for (i=0; str[i]!='\0'; i++)
    {
	if (str[i]==' ')
	{
	    str1[k][j] = '\0';
	    k++;
	    j=0;
	}
	else
	{
	    str1[k][j]=str[i];
	    j++;
	}
    }
    str1[k][j] = '\0';
    cout<<"Enter a word to be delete : ";
    cin>>word;

    /* Comparing the string with the given word */

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

    }
    cout<<"The new String after deleting the word : \n";
    for (i=0; i<k+1; i++)
    {
		cout<<str1[i]<<" ";
    }
    getch();
}

When the above C++ program is compile and executed, it will produce the following result:

C++ program to delete word from string sentence

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test