#include <iostream>
#include <vector>
void split(const std::string& src, const std::string& delim, std::vector< std::string >& ret)
{
size_t last = 0;
size_t index = src.find_first_of(delim, last);
while (index != std::string::npos)
{
ret.push_back(src.substr(last, index - last));
last = index + 1;
index = src.find_first_of(delim, last);
}
if (index - last > 0)
{
ret.push_back(src.substr(last, index - last));
}
}
int main(int argc, char** argv)
{
std::string str = "123,abcd,ooo";
std::vector<std::string> vecInfo;
split(str, ",", vecInfo);
std::vector<std::string>::iterator iter = vecInfo.begin();
for (; iter != vecInfo.end(); ++iter)
{
std::cout << iter->c_str() << std::endl;
}
system("pause");
}
结果:
123
abcd
ooo
本文介绍了一个使用 C++ 实现的字符串拆分函数。该函数能够根据指定的分隔符将输入字符串拆分成多个子串,并将这些子串存入一个标准模板库(STL)的 vector 容器中。随后通过一个示例展示了如何调用此函数并打印出拆分后的各个子串。


被折叠的 条评论
为什么被折叠?



