如何使用boost split拆分字符串并忽略空值
How to use boost split to split a string and ignore empty values?
我使用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);
相关文章:
- 动态更改数组的大小并读取值.(无矢量)
- 使用 const char* 键映射 C++ 检索空值
- 返回空值的字符串值
- boost::any 如何检查空值/未定义的值
- C++ - 无法从基类继承 |提供空值
- C++空值和此指针
- 使用 cin 或 getline() 输入空值
- 可变参数列表是否以空值终止?
- 如何将整数重新初始化/设置为空值
- 我想将 POST 请求从 arduino 发送到 mysql 工作台并保存值
- 接受迭代器作为参数并存储值的类?
- 调整向量大小并检索值,这是否正确或在任何情况下都可能导致段错误?
- 如果函数按值传递并按值返回,将调用复制构造函数多少次
- 我想读取文本文件中的所有内容(但文本文件中只有一个双精度值),转换为双精度值并返回值
- C++11 lambda 捕获"this"并按值捕获局部变量
- 将空数组传递给函数,在该函数中输入值并返回值的示例
- "iqueue->front"显示正确的值,而不是空值。但是tempiq显示NULL并给出分割错误。为什么?
- 如何使用boost split拆分字符串并忽略空值
- 寻找一个如何使用ODBC API将空值绑定并插入数据库的线性示例
- C++ std::unique_ptr 从函数返回并测试空值