我正在使用 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/