zoukankan      html  css  js  c++  java
  • C++从string中删除所有的某个特定字符

    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_if
    
    bool 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 << '
    ';
    
      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::vector
    
    int 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 << '
    ';
    
      return 0;
    }

    Output:

    myvector contains: 10 30 30 10 10 0 0 0
  • 相关阅读:
    iOS设备后台播放音乐方法
    iOS 编译64位FFMPEG
    os8 location authorization 错误.
    IOS 使用新浪微博SDK
    IOS 解析歌词lrc
    IOS 通过button获取cell
    IOS 解析XML文档
    OC .(点)与->(箭头)用法区别
    黑苹果安装合集
    Hello,World
  • 原文地址:https://www.cnblogs.com/testlife007/p/8365127.html
Copyright © 2011-2022 走看看