使用std :: remove删除错误的字符

时间:2013-01-27 12:28:41

标签: c++ string std cut

  

可能重复:
  Remove spaces from std::string in C++
  std::remove does not work

我使用std :: remove从字符串中删除一些字符。 例如:

std::string hash_value = "3f-2b-d6-ab-aa-6d-62-b4-ce-6f-6b-2f-21-4c-99-fc";
std::remove(hash_value.begin(), hash_value.end(), '-');

hash_value大小必须为32并且值为:

  

3F2BD6ABAA6D62B4CE6F6B2F214C99FC

但它的大小和价值是:

  

3F2BD6ABAA6D62B4CE6F6B2F214C99FC-2F-21-4C-99-FC

你能帮助我吗,我做错了什么? 谢谢!

3 个答案:

答案 0 :(得分:4)

您需要使用remove-erase idiom。 std :: remove只将元素移动到容器的末尾,之后需要将它们删除。

hash_value.erase(std::remove(hash_value.begin(), hash_value.end(), '-'), hash_value.end());

答案 1 :(得分:2)

std::remove重新排列序列的内容,以便“removed”元素位于末尾,其中end定义为函数返回的迭代器与序列末尾之间的范围。如果您想缩短序列,请使用erase-remove idiom

hash_value.erase(std::remove(hash_value.begin(), hash_value.end(), '-'), hash_value.end()); 

答案 2 :(得分:0)

该函数不能改变包含元素范围的对象的属性(即,它不能改变数组或容器的大小):通过用下一个元素替换等于val的元素来完成删除但是没有,并通过将迭代器返回到应该被视为新的过去元素的元素来发出缩短范围的新大小。

例如,请查看以下与std :: remove

相关的示例

int myints [] = {10,20,30,30,20,10,10,20}; // 10 20 30 30 20 10 10 20

//范围界限:

int * pbegin = myints; // ^

int * pend = myints + sizeof(myints)/ sizeof(int);

// pend现在指向容器(逻辑)端

pend = std :: remove(pbegin,pend,20);

std :: cout<< “范围包含:”;

for(int * p = pbegin; p!= pend; ++ p)

std :: cout<< ''<< * P

将显示

范围包含:10 30 30 10 10