将std :: string拆分为vector <string>的正确方法

将字符串拆分为字符串向量的正确方法是什么。分隔符是空格或逗号。



扬帆大鱼
浏览 1679回答 3
3回答

茅侃侃

vector<string> split(string str, string token){&nbsp; &nbsp; vector<string>result;&nbsp; &nbsp; while(str.size()){&nbsp; &nbsp; &nbsp; &nbsp; int index = str.find(token);&nbsp; &nbsp; &nbsp; &nbsp; if(index!=string::npos){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.push_back(str.substr(0,index));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; str = str.substr(index+token.size());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(str.size()==0)result.push_back(str);&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.push_back(str);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; str = "";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result;}split(“ 1,2,3”,“,”)==> [“ 1”,“ 2”,“ 3”]split(“ 1,2,”,“,”)==> [“ 1”,“ 2”,“”]split(“ 1token2token3”,“ token”)==> [“ 1”,“ 2”,“ 3”]
打开App,查看更多内容
随时随地看视频慕课网APP