0

Let's say I have an input file and an output file. The input file reads something like this when I open it:

Happy birthday to everyone!

Then I enter a string that I want to remove from the string from the data that was read and write it to the output file. For example, if I remove 'at', I will get this:

Hppy birhdy o everyone!

How can I use str.erase or another string method to do this?

Mary
  • 211
  • 1
  • 8
  • 18
  • 1
    std::string::erase removes characters from a between two locations. std::remove_if can remove one specific character value or take a lambda that matches more than one. std::regex and std::regex_replace can match whatever you want and remove it. If you want to use std::remove_if take a look at http://stackoverflow.com/questions/5891610/how-to-remove-characters-from-a-string – Jerry Jeremiah Aug 28 '15 at 04:29

2 Answers2

1
#include <string>
#include <algorithm>

static bool is_a_t(char c) { return c == 'a' || c == 't'; }

std::string in("Happy birthday to everyone!");
in.erase(std::remove_if(in.begin(), in.end(), is_a_t), in.end());
timrau
  • 22,578
  • 4
  • 51
  • 64
  • Considering the time complexity of `std::remove_if`, I would rather make a new copy :P – Lingxi Aug 28 '15 at 04:29
  • Both of them are of linear time, aren't they? In-place modification even saved the reallocation effort. – timrau Aug 28 '15 at 04:30
1
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>

std::string get_processed_copy(const std::string& src, const std::string& remove) {
    std::string dst;
    std::remove_copy_if(src.begin(), src.end(), std::back_inserter(dst),
        [&](char c) {
            return remove.find(c) != remove.npos;
        });
    return dst;
}

int main() {
    std::cout << get_processed_copy("Happy birthday to everyone!", "at") << std::endl;
}
Lingxi
  • 14,579
  • 2
  • 37
  • 93
  • What if the data from the file is read character by character and placed into an array? – Mary Aug 28 '15 at 05:07
  • `std::basic_string` has a constructor overload that takes in a null-terminated character array. See overload (5) in http://en.cppreference.com/w/cpp/string/basic_string/basic_string. – Lingxi Aug 28 '15 at 05:20