简体   繁体   中英

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!

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM