C++ split函数

#include<iostream>
#include<vector>
#include<sstream>
using namespace std;

vector<string> split(string s,char token){
    istringstream iss(s);
    string word;
    vector<string> vs;
    while(getline(iss,word,token)){
        vs.push_back(word);
    }
    return vs;
}

vector<string> split_black_space(string s){
    stringstream ss;
    ss<<s;//存到字符流里
    vector<string> vs;
    string word;
    while(ss>>word){//从字符流里读单词,会天然地过滤到多余的空格
        vs.push_back(word);
    }
    return vs;
}

int main(){
    string s1="I am a    good     boy.";
    cout<<"test string: "<<endl;
    cout<<s1<<endl;
    cout<<"test split_black_space:"<<endl;
    vector<string> vs = split_black_space(s1);//会跳过多余的空格
    for(auto seh:vs)
        cout<<seh<<" ";
    cout<<endl;
    cout<<"test split:"<<endl;
    vs = split(s1,' ');
    for(auto seh:vs)//这个会有空的,再加上后面的' ',就会和s1一样,这个split并不会跳过多余的空格
        cout<<seh<<" ";
    cout<<endl;
    string s2="A//B//C//D//E";
    cout<<s2<<endl;
    vs = split(s2,'/');
    for(auto seh:vs)//这个会有空的,再加上后面的' ',就会和s2一样宽
        cout<<seh<<" ";
    cout<<endl;
    string s3="A/B/C/D/E";
    cout<<s3<<endl;
    vs = split(s3,'/');
    for(auto seh:vs)
        cout<<seh<<" ";
    cout<<endl;
}
可以改成传引用的版本,效率会高一些。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值