I have a string = "abcdefg". I will copy it to another string inside a loop. Then I want to erase only one character every time. First I will remove the character a from the first and it will be "bcdefg". Second time I will remove b and the string will be "acdefg". And so on. I tried to do it using erase() but it didn't work. You may take a look at how I tried:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main() {
string abc = "abcdefg"; // the main string
int len = abc.length();
for(int i=0;i<len;i++)
{
string cba = abc; // I copy it to another string
cba.erase(i,i+1); // I try to erase only one element
cout<<cba<<endl;
}
return 0;
}
The output should be:
bcdefg
acdefg
abdefg
abcefg
abcdfg
abcdeg
abcdef
But my code prints:
bcdefg
adefg
abfg
abc
abcd
abcde
abcdef
Can anybody please suggest me a way to do it correctly?? I'm really in danger.
The
std::basic_string::erase
function you are calling takes an index and a count. The second parameter is the number of characters to remove and you should be using1
.