gpt4 book ai didi

c++ - boost::split 仅当 C++ 中存在分隔符时才拆分

转载 作者:行者123 更新时间:2023-12-04 07:53:31 26 4
gpt4 key购买 nike

我正在使用 boost::split但如果字符串没有分隔符,则它返回 vector 中的字符串。如果字符串中没有分隔符,我希望它不返回任何内容。

#include <iostream>
#include <string>
#include <bits/stdc++.h>
#include <boost/algorithm/string.hpp>
using namespace std;

int main()
{
string input("abcd");
vector<string> result;
boost::split(result, input, boost::is_any_of("\t"));

for (int i = 0; i < result.size(); i++)
cout << result[i] << endl;
return 0;
}
输出是 abcd。如果字符串中不存在分隔符,我希望 vector 为空。请建议。

最佳答案

看起来您可能需要一个验证解析器。正则表达式可能是一个很好的起点,但我建议使用解析器生成器,因为您很可能需要更多

My crystal ball whispers that you might be parsing command line output or CSV/TSV files


这就是你可以用 Boost Spirit X3 做的事情:
template <typename Cont>
bool parse_columns(std::string_view input, Cont& container,
unsigned required = 2) {
namespace x3 = boost::spirit::x3;

auto valid = [required](auto& ctx) {
x3::_pass(ctx) = x3::_val(ctx).size() >= required;
};

auto delim = x3::char_('\t');
auto field = *(~delim);
auto rule
= x3::rule<struct _, Cont, true>{"rule"}
= (field % delim)[valid];

return parse(begin(input), end(input), rule, container);
}
这是一个带有测试用例的现场演示:
Live On Compiler Explorer
#include <boost/spirit/home/x3.hpp>
#include <fmt/ranges.h>

template <typename Cont>
bool parse_columns(std::string_view input, Cont& container,
unsigned required = 2) {
namespace x3 = boost::spirit::x3;

auto valid = [required](auto& ctx) {
x3::_pass(ctx) = x3::_val(ctx).size() >= required;
};

auto delim = x3::char_('\t');
auto field = *(~delim);
auto rule
= x3::rule<struct _, Cont, true>{"rule"}
= (field % delim)[valid];

return parse(begin(input), end(input), rule, container);
}

int main() {
for (auto input : {
"",
"\t",
"abcd\t",
"ab cd\tef",
"\tef",
"ab\tc\t\tdef",
"abcd",
}) {
std::vector<std::string> columns;

if (parse_columns(input, columns)) {
fmt::print("'{}' -> {}\n", input, columns);
} else {
fmt::print("'{}' -> not matched\n", input);
}
}
}
打印
'' -> not matched
' ' -> {"", ""}
'abcd ' -> {"abcd", ""}
'ab cd ef' -> {"ab cd", "ef"}
' ef' -> {"", "ef"}
'ab c def' -> {"ab", "c", "", "def"}
'abcd' -> not matched
调整
  • 治疗重复\t作为单个分隔符,只需更改 field % delimfield % +delim
  • 您可以轻松地替换为另一个容器,例如 std::set

  • Live On Compiler Explorer

    关于c++ - boost::split 仅当 C++ 中存在分隔符时才拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66823146/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com