C++從string中刪除所有的某個特定字元

來源:互聯網
上載者:User

標籤:post   ref   it!   com   一個   元素   迭代   algo   span   

C++中要從string中刪除所有某個特定字元, 可用如下代碼

str.erase(std::remove(str.begin(), str.end(), ‘a‘), str.end());

其中, remove來自<algorithm>, 它的簽名是

template <class ForwardIterator, class T>  ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);

作用: 在容器中, 刪除[first, last)之間的所有值等於val的值.

刪除方法: 將某個等於val的值用下一個不等於val的值覆蓋.

傳回值: 一個迭代器 (記作newEnd), 該迭代器指向最後一個未被刪除元素的下一個元素, 即相當於容器新的end.

所以, 運行完remove後, 容器的[first, newEnd)內的元素即為所有未被刪除的元素, [newEnd, end)之間的元素已經沒用了.

這樣, 再運行str.erase(newEnd, str.end())即可清空[newEnd, end)之間的元素.

std::remove_ifremove類似, 只是它接受的第三個參數是個函數.

// remove_if example#include <iostream>     // std::cout#include <algorithm>    // std::remove_ifbool IsOdd (int i) { return ((i%2)==1); }int main () {  int myints[] = {1,2,3,4,5,6,7,8,9};            // 1 2 3 4 5 6 7 8 9  // bounds of range:  int* pbegin = myints;                          // ^  int* pend = myints+sizeof(myints)/sizeof(int); // ^                 ^  pend = std::remove_if (pbegin, pend, IsOdd);   // 2 4 6 8 ? ? ? ? ?                                                 // ^       ^  std::cout << "the range contains:";  for (int* p=pbegin; p!=pend; ++p)    std::cout << ‘ ‘ << *p;  std::cout << ‘\n‘;  return 0;}

Output:

myvector contains: 10 30 30 10 10 0 0 0

還有個std::remove_copy, 簽名:

template <class InputIterator, class OutputIterator, class T>  OutputIterator remove_copy (InputIterator first, InputIterator last,                              OutputIterator result, const T& val);

它會把[first, last)之間不等於val的元素都向從result開始的容器拷貝.

// remove_copy example#include <iostream>     // std::cout#include <algorithm>    // std::remove_copy#include <vector>       // std::vectorint main () {  int myints[] = {10,20,30,30,20,10,10,20};               // 10 20 30 30 20 10 10 20  std::vector<int> myvector (8);  std::remove_copy (myints,myints+8,myvector.begin(),20); // 10 30 30 10 10 0 0 0  std::cout << "myvector contains:";  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)    std::cout << ‘ ‘ << *it;  std::cout << ‘\n‘;  return 0;}

Output:

myvector contains: 10 30 30 10 10 0 0 0

C++從string中刪除所有的某個特定字元

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.