本文主要参考自cplusplus中的《Split a String》 一文。
在别的一些语言中,包括Python,C#等语言中,字符串的分割都提供了标准的函数,但是C++没有提供相关的函数。
举个例子,给定一个字符串str = "the quick brown fox" will be splitted by " ",调用函数split(str, " ") ,然后会返回{"the", "quick", "brown", "fox"}.
这里使用C++实现split函数,代码如下:
其中使用了C++11的特性,包括范围for循环和列表初始化。
const vector<string> split(const string& s, const char& c)
{
string buff{ "" };
vector<string> v;
for (auto n : s)
{
if (n != c) buff += n; else
if (n == c && buff != "") { v.push_back(buff); buff = ""; }
}
if (buff != "") v.push_back(buff);
return v;
}
下面代码演示了如何调用该函数:
int main()
{
string str{ "the quick brown fox jumps over the lazy dog" };
vector<string> v{ split(str, ' ') };
for (auto n : v) cout << n << endl;
return 0;
}
输出结果如下:
the
quick
brown
fox
jumps
over
the
lazy
dog