我想通过来拆分一个字符串and
。
首先,我必须明确指出,我不打算将任何regex
字符用作分隔符。
我运行以下代码:
#include <iostream>
#include <regex>
#include <boost/algorithm/string.hpp>
int main()
{
std::vector<std::string> results;
std::string text=
"Alexievich, Svetlana and Lindahl,Tomas and Campbell,William";
boost::split(
results,
text,
boost::is_any_of(" and "),
boost::token_compress_off
);
for(auto result:results)
{
std::cout<<result<<"\n";
}
return 0;
}
结果与我期望的不同:
Alexievich,
Svetl
Li
hl,Tom
s
C
mpbell,Willi
m
似乎定界符中的每个字符都是单独起作用的,而我需要将整体and
作为定界符。
老式的方式:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> results;
std::string text=
"Alexievich, Svetlana and Lindahl,Tomas and Campbell,William";
size_t pos = 0;
for (;;) {
size_t next = text.find("and", pos);
results.push_back(text.substr(pos, next - pos));
if (next == std::string::npos) break;
pos = next + 3;
}
for(auto result:results)
{
std::cout<<result<<"\n";
}
return 0;
}
打包成可重用的功能留给读者练习。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句