如何使用boost split拆分字符串并忽略空值

How to use boost split to split a string and ignore empty values?

本文关键字:串并 空值 字符串 字符 何使用 boost split 拆分      更新时间:2023-10-16

我使用boost::split来解析数据文件。数据文件包含如下行:

data.txt

1:1~15  ASTKGPSVFPLAPSS SVFPLAPSS   -12.6   98.3    

条目之间的空白是制表符。我必须将上面的代码分割如下:

std::string buf;
/*Assign the line from the file to buf*/
std::vector<std::string> dataLine;
boost::split( dataLine, buf , boost::is_any_of("t "), boost::token_compress_on);       //Split data line
cout << dataLine.size() << endl;

对于上面的代码行,我应该打印出5,但我得到6。我试图通过阅读文档和这个解决方案似乎好像它应该做我想要的,显然我错过了一些东西。谢谢!

编辑:在dataLine上运行一个forloop,你会得到如下结果:

cout << "****" << endl;
for(int i = 0 ; i < dataLine.size() ; i ++) cout << dataLine[i] << endl;
cout << "****" << endl;

****
1:1~15
ASTKGPSVFPLAPSS
SVFPLAPSS
-12.6
98.3
****

尽管"相邻分隔符合并在一起",但似乎是后面的分隔符造成了问题,因为即使它们被视为一个分隔符,仍然是一个分隔符。

所以你的问题不能单独用split()来解决。但幸运的是,Boost字符串算法有trim()trim_if(),从字符串的开始和结束剥离空白或分隔符。所以只需调用trim() on,像这样:

std::string buf = "1:1~15  ASTKGPSVFPLAPSS SVFPLAPSS   -12.6   98.3    ";
std::vector<std::string> dataLine;
boost::trim_if(buf, boost::is_any_of("t ")); // could also use plain boost::trim
boost::split(dataLine, buf, boost::is_any_of("t "), boost::token_compress_on);
std::cout << out.size() << std::endl;

这个问题已经问过了:boost::split在字符串的开始和结束处留下空标记-这是期望的行为吗?

我建议使用c++ String Toolkit Library。在我看来,这个库比Boost快得多。我曾经使用Boost拆分(又名tokenize)一行文本,但发现这个库更符合我想要的。

strtk::parse的一个伟大之处在于它将标记转换为最终值并检查元素的数量。

你可以这样用:

std::vector<std::string> tokens;
// multiple delimiters should be treated as one
if( !strtk::parse( dataLine, "t", tokens ) )
{
    std::cout << "failed" << std::endl;
}

—另一个版本

std::string token1;
std::string token2;
std::string token3:
float value1;
float value2;
if( !strtk::parse( dataLine, "t", token1, token2, token3, value1, value2) )
{
     std::cout << "failed" << std::endl;
     // fails if the number of elements is not what you want
}

库的在线文档:字符串标记器文档源代码链接:c++ String Toolkit Library

boost::split故意不使用前导和尾随的空白,因为它不知道它是否有效。解决方案是在调用boost::split之前使用boost::trim

#include <boost/algorithm/string/trim.hpp>
....
boost::trim(buf);