#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;
}
可以改成传引用的版本,效率会高一些。
C++ split函数
最新推荐文章于 2025-03-02 10:44:18 发布