Search code examples
c++stringerase

string.erase function is not working in a specific case


I have strings of the following format: "name.bag.csv" I would like to remove the ".bag" from the string. This is an example of the code that I am trying to run:

csv_file_name = "loololololool.bag.csv";
csv_file_name.erase(csv_file_name.end()-8, 4);
std::cout << csv_file_name << std::endl;

But I get an error on the second line:

 no matching function for call to ‘std::__cxx11::basic_string<char>::erase(__gnu_cxx::__normal_iterator<char*, std::__cxx11::basic_string<char> >, int)’
         csv_file_name.erase(csv_file_name.end()-8, 4);

It seems to only take one argument. However if I do:

csv_file_name = "loololololool.bag.csv";
csv_file_name.erase(13, 4);
std::cout << csv_file_name << std::endl;

it seems to work fine. Also when I execute

csv_file_name = "loololololool.bag.csv";
csv_file_name.erase(csv_file_name.end()-8);
std::cout << csv_file_name << std::endl;

It deletes the single character as it should. How can this happen? The csv_file_name.end()-8 must be working as it deletes the single character. And taking two arguments should be working as well. But the combination doesn't? Please help!


Solution

  • You are mixing up iterators and indexes.

    • string.erase(iter) // delete the character pointed to by the iterator

    • string.erase(iter1, iter2) // delete the characters between the two iterators

    • string.erase(index, count) // delete count characters starting at index

    csv_file_name.end()-8 is an iterator and there is no version of erase that takes an iterator and an index or count.

    Instead of

    csv_file_name.erase(csv_file_name.end()-8, 4);
    

    I think you meant

    csv_file_name.erase(csv_file_name.size()-8, 4);
    

    But really you should be able to read documentation and figure this stuff out for yourself. You'll be a lot more efficient that way.