C++ 删除字符串中的某些特定字符,及对字符串用某些特定的字符划分为vector<string>

#include <iostream>
#include <string.h>
#include <vector>

using namespace std;

void delete_somechar(string &a, string &b) // 删除字符串a中的字符串b中的所有字符
{
    for (int i = 0; i < b.length(); i++)
    {
        for (string::iterator it = a.begin(); it < a.end(); it++)
        {
            if (*it == b[i])
            {
                a.erase(it);
                it--; /* 因为it迭代器指向的字符被删除后会自动前移,所以此处需要it--,以免for循环中的it++跳过某个字符*/
            }
        }
    }
}

vector<string> split(const string &str, const string &delim) //  对字符串 str 用 字符串 delim 进行分割
{
    vector<string> res;
    if ("" == str) return res;
    char *p = strtok((char *)str.c_str(), delim.c_str()); // 先将要切割的字符串从string类型转换为char*类型
    while (p)
    {
        string s = p;     // 分割得到的字符串转换为string类型
        res.push_back(s); // 存入结果数组
        p = strtok(NULL, delim.c_str());
    }
    return res;
}

int main()
{
    string a, b;
    // getline(cin,a);    //读入原字符串
    // getline(cin,b);    //读入需要被删除的一些字符
    a = "[\"green\", \"yellow\", \"red\"]";
    b = "[ ]\"";

    delete_somechar(a, b);
    const char *delim = ",";
    vector<string> p = split(a, delim);
    for (int i = 0; i < p.size(); i++)
    {
        cout << p[i] << endl;
    }
    return 0;
}

// g++ demo.cc -o demo

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值