C++ 分割字符串(包括含有连续分隔符)
网上很多教程都是分割字符串,但是不能正确分割含有连续分隔符得字符串,比如分割:
" I u0 fdfsdf fdsdaas q.qwwqe 3213 3213 ^^ ^ ",里面有多个连续空格,正确分割后如下:
std::vector<std::string> splitString(const std::string str, const char chrc)
{
std::vector<std::string> res;
if (str == "")return res; //判空
std::string strs = str + chrc; //末尾加上分隔符方便计算
size_t size = strs.size();
size_t pos{ 0 }; //分割位置
bool meet{ false }; //分隔符连续标志位
for (size_t i = 0; i <= size; i++)
{
if (strs[i] != chrc && !meet)
{
pos = i;
meet = true;
}
if (strs[i] == chrc && meet)
{
res.push_back(strs.substr(pos, i - pos));
pos = i;
meet = false;
}
}
return res;
}
int main()
{
const std::string str = " I u0 fdfsdf fdsdaas q.qwwqe 3213 3213 ^^ ^ ";
for (auto p : splitString(str, ' '))
{
std::cout << p << '\n';
}
system("Pause");
return 0;
}