Search code examples
c++charswitch-statementerase-remove-idiom

Removing chars from an array of chars in C++


I am trying to create a way to remove a substring from a string. It is in char form so I can't use convenient means of that are gleefully given to strings. I know how to search for it, I can locate the index but man deleting a char has been a bit of a venture for me. If anyone has any ideas I would greatly appreciate it. Thanks.

#include "stdafx.h"
#include <iostream>
#include <cstring>


using namespace std;

char str[20];
char del[20];
char * delStorage;

char select(char);

int main()
{
    cout << "Enter a string to the console." << endl;
    cin >> str;
    cout << "You inputted " << str << " for the string." << endl;


    select(letter);

return 0;
}

char select(char letter)
{
    cout << "Enter one of the following commands d for delete." << endl;
    cin >> letter;
    switch (letter)

{
case 'D':
case 'd':
    cout << "Enter a string to delete." << endl;
    cin >> del;
    delStorage = strstr(str, del);
    if (delStorage)
    {
        cout << del << " has been found.  Deleting..." << endl;
        delStorage.Replace(str, del, "");

    }
    break;
}

I can't use the Replace method due to it being in character. I've tried the nested loop but get stuck due to the incompatibility of char and int. If anyone has a suggestion I am all ears. Thanks again Stack community.


Solution

  • Not a complete answer, since this looks like a homework problem you want to solve yourself. Here's a solution using low-level pointers, but you could adapt it to use iterators.

    Keep a left pointer and a right pointer. The right pointer should be const char *. As you iterate through the string, if you see a possible beginning of the substring, increment the right pointer but not the left. if it turns out not to be the substring (fog, not foo), set the left pointer to the right pointer and keep searching. If it was the substring, copy the string beginning at the right pointer, which now is one past the end of the substring, over the substring, to the place marked by your left pointer. If you reach the end of the string, stop.