Delete Characters

Can someone help me so that the program takes in a phrase and can delete a character/word/phrase? Thanks


#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char Word[300];
char Delete = ' ';

cout << "Enter a word: ";
cin >> Word;

cout << "Enter a character you want to delete: ";
cin >> Delete;

int strLen = strlen(Word);
for(int i = 0; i < strLen; i++)
{
if(Delete == Word[i])
{
for(int j=i;j<(strLen -1);j++)
Word[j]=Word[j+1];
strLen--;
Word[strLen]='\0';
}
}

cout << Word << endl << endl;

system("PAUSE");
return 0;
}
if you want to get input that has spaces just use the getline() function.
goes like:

cin.getline(variable, max characters to be entered, terminating character);

generally looks something like:
 
cin.getline(word, 15, '\n');
You just need to decrement "i" by one.
1
2
3
4
5
6
7
8
9
10
11
for(int i = 0; i < strLen; i++) 
{
    if(Delete == Word[i]) 
    { 
        for(int j=i;j<(strLen -1);j++)
            Word[j]=Word[j+1];
        strLen--; 
        Word[strLen]='\0'; 
        --i; // There is a new character at Word[i], so don't move to the next yet
    }
}
Last edited on
Topic archived. No new replies allowed.