schusterj
schusterj

Reputation: 13

Deleting characters from a string

I am trying to delete certain characters from a string.

My code is:

#include <string>
#include <iostream>

int main (int argc, char* argv[]) {
    string x = "hello";
    string y = "ell";

    string result = x.erase( x.find(y), (x.find(y)) + y.length() - 1 );
    cout << result << endl;

    return 0;
 }

and it gives the desired output of:

ho

But when I change the strings to

#include <string>
#include <iostream>

int main (int argc, char* argv[]) {
    string x = "Xx";
    string y = "Xx";

    string result = x.erase( x.find(y), (x.find(y)) + y.length() - 1 );
    cout << result << endl;

    return 0;
}

it prints out

x

Instead of the desired output of nothing. I believe it has something to do with the way erase(), find(), and length() all count characters (from 0 or from 1) but I couldn't find anything in the documentation. Any help is greatly appreciated!

Upvotes: 1

Views: 89

Answers (1)

Slava
Slava

Reputation: 44238

You use first variant of std::string::erase

basic_string& erase( size_type index = 0, size_type count = npos );

second parameter is count not position, so just use y.length():

string result = x.erase( x.find(y), y.length() );

it "works" in first case from your example in coincidence.

live example

Upvotes: 2

Related Questions