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

标签 c++ parsing boost split

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

数据.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 String Algo 有 trim() and trim_if() ,从字符串的开头和结尾去除空格或分隔符。所以只需在 buf 上调用 trim(),如下所示:

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 leaves empty tokens at the beginning and end of string - is this desired behaviour?

关于c++ - 如何使用 boost split 拆分字符串并忽略空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15690389/

相关文章:

c++ - 在结构中使用 typedef 来命名和索引文本命令

c++ - 重构以下两个C++方法,移出重复代码

c++ - QStateMachine如何在不同的QState中显示和隐藏QGraphicsView和QObject

java - 如何在Java中读写没有某些节点的XML文件

python - python 和 regex 模块如何处理反斜杠?

c++ - 如何使 FindBoost.cmake 工作?

c++ - c++ 类的 objective-c 链接器错误

java - 解析来自 Dentrix 桌面应用程序的信息

c++ - 如何在 visual studio 2010 中使用 boost::multiprecision::float128

c++ - 在 CMake header-only library 中生成 "stores"它对 boost 文件系统的依赖