您的位置:首页 > 编程语言 > C语言/C++

C++:实现split分割字符串 - 改进

2015-08-18 17:45 726 查看
</pre><pre name="code" class="cpp">int split(const string& src, const string& separator, vector<string>& dest)
{
string::size_type pos = 0;
string::size_type start = 0;

dest.clear();

do{
start = src.find_first_not_of(separator, pos);
if (start == string::npos)
break;

pos = src.find_first_of(separator,start);
if(pos != string::npos)
{
dest.push_back(src.substr(start, pos-start));
}
else
{
dest.push_back(src.substr(start));
break;
}
}while(1);

return dest.size();
}
int main(void)
{
int cnt;

string str = "  hello,xxx     fk sjf lj\n";
string sep = ", ";

vector <string> dest;

cnt = split(str, sep, dest);

for(int i=0; i<cnt; i++)
{
printf("%s\n", dest[i].c_str());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: