有没有办法在遇到空行时使用 boost::split 来分割字符串?
这是我的意思的一个片段。
std::stringstream source; source.str(input_string); std::string line; std::getline(source, line, '\0'); std::vector<std::string> token; boost:split(token,line, boost::is_any_of("what goes here for blank line");
最佳答案
您可以按双 \n\n
分割,除非您将空行表示为“可能包含其他空白的行”。
<强> Live On Coliru
#include <boost/regex.hpp>
#include <boost/algorithm/string_regex.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <sstream>
#include <iostream>
#include <iomanip>
int main() {
std::stringstream source;
source.str(R"(line one
that was an empty line, now some whitespace:
bye)");
std::string line(std::istreambuf_iterator<char>(source), {});
std::vector<std::string> tokens;
auto re = boost::regex("\n\n");
boost::split_regex(tokens, line, re);
for (auto token : tokens) {
std::cout << std::quoted(token) << "\n";
}
}
打印
"line one"
"that was an empty line, now some whitespace:
bye"
在“空”行上允许有空格
用正则表达式表达即可:
auto re = boost::regex(R"(\n\s*\n)");
现在输出是: Live On Coliru
"line one"
"that was an empty line, now some whitespace:"
"bye"
关于c++ - 通过空行 boost 分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62491337/