c++ - 使用多个定界符拆分字符串,允许引用值

标签 c++ string boost boost-tokenizer

docs对于 boost::escaped_list_separator 为第二个参数 c 提供以下解释:

Any character in the string c, is considered to be a separator.

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

#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]。但是,他的代码results在一堆空 token 中:

enter image description here

常规 boost::char_separator 忽略所有这些空标记,考虑所有分隔符。 boost::escaped_list_separator 似乎也考虑了所有指定的定界符,但生成的是空值。是不是如果遇到多个连续的定界符,就会产生空的token?有什么办法可以避免这种情况吗?

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

最佳答案

根据 Boost Tokenizer 文档判断,您假设如果遇到多个连续的定界符,使用 boost::escaped_list_separator 时将生成空标记,这确实是正确的。与 boost::char_separator 不同,boost::escaped_list_separator 不提供任何允许您传入是保留还是丢弃生成的任何空标记的构造函数。

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

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

关于c++ - 使用多个定界符拆分字符串,允许引用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43667849/

相关文章:

c++ - 对象 move 后,指向const vector 成员变量元素的指针是否保持稳定?

c++ - Qt 如何设置最小化的子窗口出现在父窗口内?

c++ - Boost Lambda/Phoenix - 如何做返回另一个 lambda 的 lambda?

string - 为什么在Golang中使用逗号和下划线。解释以下代码中的第12行?

string - dw 和 dd 与字符串的 db 指令有何不同?

Qt 相当于 boost::shared_from_this?

c++ - C++ 的 XML 数据绑定(bind)类似于 Java 的 JAXB

c++ - 私有(private)子句中的变量与 OpenMP 中并行区域中定义的变量之间有什么区别吗?

c++ - 为将来的 QThreadPool 线程和/或 pthread_create 调用设置默认堆栈大小

c++ - 当我们尝试使用 istream::getline() 和 std::getline() 提取文件中出现 `eof` 字符的行时,实际会发生什么