Erase only one element of a string(C++)

379 views Asked by At

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.

2

There are 2 answers

0
Blastfurnace On BEST ANSWER

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 using 1.

0
Mark M On

For some example code:

//M a r k
//0 1 2 3
string name = "Mark"; 
//erase the single character 'r' at position 2
name.erase(2, 1); //M a k