2

I'm new to C++. I know there is an std::remove method to remove characters from a string, but is there a remove_at method of some kind that will allow me to remove the characters at a certain index in the string? For example,

string s = "aBcDeF";
s = s.remove_at(4).remove_at(2);

would result in

"aBDF"

Is there a function in the standard library to do this?

Community
  • 1
  • 1
James Ko
  • 32,215
  • 30
  • 128
  • 239

3 Answers3

6

This method is called erase. Here is a demonstrative program

#include <iostream>
#include <string>

int main() 
{
    std::string s = "aBcDeF";
    s.erase( 4, 1 ).erase( 2, 1 );

    std::cout << s << std::endl;
}

The program output is

aBDF

Take into account the order in which the method is called. Of course you could split this one call in two separates calls.

For example

s.erase( 2, 1 );
s.erase( 3, 1 );

If you neded to create a new string you can simply initialize a new string with this one. For example

std::string t = s;
t.erase( 2, 1 );
t.erase( 3, 1 );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • I think this is great, but it deletes characters from the original string instead of returning a new one. Sorry for being ambiguous about immutability; I will update my question to reflect. – James Ko Jul 19 '15 at 15:48
  • 1
    What about creating this new modified string yourself? nothing difficult there – LBes Jul 19 '15 at 15:52
  • @JamesKo `string s2 = s;`, and the modifiying s2? – deviantfan Jul 19 '15 at 16:00
3

std::string::remove has an overload which gets the position of the character to remove and the amount of characters to remove from that position. so your code is basically

s.remove(4,1).remove(2,1);

http://www.cplusplus.com/reference/string/string/erase/

David Haim
  • 25,446
  • 3
  • 44
  • 78
2

http://www.cplusplus.com/reference/string/string/erase/

The first overload will do what you want. std::string has quite a few useful methods, and I'm sure not too many people can remember them all. A handy reference: http://www.cplusplus.com/reference/string/string/

mock_blatt
  • 955
  • 5
  • 11