Write a C++ program to delete words from a sentence, where sentence is entered by user.
Program Code:
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
int i, j = 0, k = 0, count = 0;
char str[100], str1[10][20], word[20];
cout<<"Enter the sentence to delete words from : ";
gets(str);
cout<<endl;
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 from the sentence : ";
cin>>word;
cout<<endl;
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 from the sentence : ";
for (i=0; i<k+1; i++)
{
cout<<str1[i]<<" ";
}
return 0;
}
The program output is tested on www.jdoodle.com
Output:
Enter the sentence to delete words from : Mukesh Rajput Mukesh
Enter a word to be delete from the sentence : Mukesh
The new String after deleting the word from the sentence : Rajput
Thanks
Mukesh Rajput
Post A Comment:
0 comments: