C++基于getline的split实现

前言

C++ 作为老大哥竟然一直不支持 split ,在看程设模拟的时候发现了可以通过 getline 优雅的实现 split。

代码

vector<string> split(const string& s, char c) {  //分隔文件名
    vector<string> res;
    string tmp;
    stringstream ss(s);
    while (getline(ss, tmp, c)) res.push_back(tmp);  //res保存整体
    return res;
}
// std::vector<std::string> split(const std::string& line, char c) {
//     std::stringstream stm(line);
//     std::vector<std::string> ans;
//     std::string tmp;
//     while (std::getline(stm, tmp, c)) ans.push_back(tmp);
//     return ans;
// }
int main() {
    // ios::sync_with_stdio(false);
    // cout.tie(NULL);
    string s;
    while (cin >> s) {
        vector<string> V = split(s, '/');
        cout << V.size() << " ";
        for (auto& it : V) {
            cout << it << " ";
        }
        cout << endl;
    }
    return 0;
}

input

a/bb/cc
a/bb/cc/
a/bb/cc-c//c

output

3 a bb cc 
3 a bb cc 
5 a bb cc-c  c 

解释

basic_istream& getline( char_type* s, std::streamsize count, char_type delim );

从流释出字符,直至行尾指定的分隔符 delim

参考链接:

cppreference

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值