[英]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.
我认为这与所有计数字符(从0或从1开始)的delete(),find()和length()方式有关,但是我在文档中找不到任何内容。 Any help is greatly appreciated!
任何帮助是极大的赞赏!
You use first variant of std::string::erase 您使用std :: string :: erase的第一个变体
basic_string& erase( size_type index = 0, size_type count = npos );
basic_string&擦除(size_type索引= 0,size_type计数= npos);
second parameter is count not position, so just use y.length()
: 第二个参数是count而不是position,因此只需使用
y.length()
:
string result = x.erase( x.find(y), y.length() );
it "works" in first case from your example in coincidence. 巧合的是,在第一种情况下,它“可以”工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.