我该如何在空格处分割字符串并返回第一个元素?例如,使用Python时可以执行以下操作:
string = 'hello how are you today'
ret = string.split(' ')[0]
print(ret)
'hello'
如果我要用C++实现这个功能,我想我需要先将字符串拆分。在网上搜索后,我看到了几种复杂的方法,但是哪种最适合像上面的代码一样工作呢?我找到的一个C++拆分字符串的示例为
#include <boost/regex.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using namespace boost;
void print( vector <string> & v )
{
for (size_t n = 0; n < v.size(); n++)
cout << "\"" << v[ n ] << "\"\n";
cout << endl;
}
int main()
{
string s = "one->two->thirty-four";
vector <string> fields;
split_regex( fields, s, regex( "->" ) );
print( fields );
return 0;
}