1

文档为第二boost::escaped_list_separator个参数提供以下解释c

字符串 c 中的任何字符都被视为分隔符。

所以,我需要用多个分隔符分割字符串,允许引用的值,其中可以包含这些分隔符:

#include <iostream>
#include <string>

#include <boost/tokenizer.hpp>

int main() {
    std::wstring str = L"2   , 14   33  50   \"AAA BBB\"";

    std::wstring escSep(L"\\"); //escape character
    std::wstring delim(L" \t\r\n,"); //split on spaces, tabs, new lines, commas
    std::wstring quotes(L"\""); //allow double-quoted values with delimiters within

    boost::escaped_list_separator<wchar_t> separator(escSep, delim, quotes);
    boost::tokenizer<boost::escaped_list_separator<wchar_t>, std::wstring::const_iterator, std::wstring> tok(str, separator);

    for(auto beg=tok.begin(); beg!=tok.end();++beg)
        std::wcout << *beg << std::endl;

    return 0;
}

预期结果将是 [2; 14; 33; 50; AAA BBB]。但是,他的代码导致一堆空标记:

在此处输入图像描述

考虑到所有分隔符, Regularboost::char_separator会忽略所有这些空标记。似乎boost::escaped_list_separator也考虑了所有指定的分隔符,但产生空值。如果遇到多个连续的分隔符,是否会产生空标记?有没有办法避免这种情况?

如果始终正确,即只生成空标记,则很容易测试结果值并手动省略它们。但是,它可能会变得非常丑陋。例如,假设每个字符串都有 2 个实际值,并且可能有许多制表符和空格分隔这些值。然后将分隔符指定为L"\t "(即空格和制表符)将起作用,但会产生大量空标记。

4

1 回答 1

3

从 Boost Tokenizer 文档来看,您确实正确地假设如果遇到多个连续的分隔符,使用boost::escaped_list_separator. 与 不同boost::char_separatorboost::escaped_list_separator不提供任何构造函数允许您传入是否保留或丢弃任何产生的空标记。

虽然可以选择丢弃空标记,但当您考虑文档(http://www.boost.org/doc/libs/1_64_0/libs/tokenizer/escaped_list_separator 中提供的用例(解析 CSV 文件)时)。 htm ),保留空标记非常有意义。一个空的字段仍然是一个字段。

一种选择是在标记化后简单地丢弃空标记。如果您关心空标记的生成,另一种方法是在将重复分隔符传递给标记器之前删除重复的分隔符,但显然您需要注意不要删除引号内的任何内容。

于 2017-04-27T22:13:55.260 回答