如何删除字符串中的字符

How to delete characters in a string?

本文关键字:字符串 字符 删除 何删除      更新时间:2023-10-16

我正在尝试编写一个程序,删除菠萝中的字符'p'以输出单词Pineale。这是我当前的代码。我发现类似的问题,并认为这段代码将工作,但它不是不幸的。任何帮助都是感激的!

    #include <iostream>
    #include <algorithm>
    #include <string>
    #include <cstdlib>
    #include <limits>
    using namespace std;
    int main(){
        remove(c,s);
    }
    string remove(char c, const string & s){
    string s = "Pineapple";
    char chars[] = "p";
    for (unsigned int i = 0; i < strlen(chars); ++i)
     {
        s.erase(remove(s.begin(), s.end(), chars[i]), s.end());
     }
     cout << s << endl;
     return s;
    }

首先,您没有定义任何c或s变量。其次,remove函数中的参数是const,这意味着s是不可改变的。下面的代码可以在我的VS2013中工作。

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <limits>
using namespace std;
string remove(char* charToRemove, string &str){
    //string s = "Pineapple";
    //char chars[] = "p";
    for (unsigned int i = 0; i < strlen(charToRemove); ++i)
    {
        str.erase(remove(str.begin(), str.end(), charToRemove[i]), str.end());
    }
    cout << str << endl;
    return str;
}
int _tmain(int argc, _TCHAR* argv[])
{
    string str("Pineapple");
    char chars[] = "p";
    remove(chars, str);
    int i;
    cin >>i;
}

简单地用string::find()"Pineapple"得到第一个'p'的位置,然后用string::erase()。不需要将string::erase()放入循环。

string remove(char to_rem, string s) {
    size_t pos = s.find( to_rem );
    s.erase(pos, count(s.begin(), s.end(), to_rem) );
    return s;
}

修改代码:

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
string remove(char to_rem, string s) {
    size_t pos = s.find( to_rem );
    s.erase(pos, count(s.begin(), s.end(), to_rem) );
    return s;
}
int main() {
    cout << remove('p', "Pineapple");
}  
输出:

Pineale

试试这个:

  struct slash_pred
    {
      char last_char;
      slash_pred()
       : last_char( '' ) // or whatever as long as it's not '/'
      {
      }
      bool operator()(char ch)
      {
          bool remove = (ch == '/') && (last_char == '/');
          last_char = ch;
      }
    };
    path.erase( std::remove_if( path.begin(), path.end(), 
          slash_pred() ), path.end() );