写一个用逗号分割string的split函数
函数原型如下void splitdou(string s,vector<string>& ret)意思就是把string对象中的字符串以逗号分割(string 中有逗号),存到容器ret中。存可以用push_back();
自己在写代码时遇到的。不是作业
我用的是c++,不是java,java中有这个函数,但是c++中没有。
程序代码:
void splitdou(string s,vector<string>& ret)
{
size_t last = 0;
size_t index=s.find_first_of(',',last);
while (index!=std::string::npos)
{
ret.push_back(s.substr(last,index-last));
last=index+1;
index=s.find_first_of(',',last);
}
if (index-last>0)
{
ret.push_back(s.substr(last,index-last));
}
}
程序代码:
// slpitdou.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "string"
#include "iostream"
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
//printf("Hello World!\n");
string st("i am, a singer,you, are, not,he is.");
vector<string> str;
string del(",");
splitdou(st,str);
for(int i=0;i<str.size();i++)
cout<<str[i]<<endl;
return 0;
}