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?
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 );
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/
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/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.