Phi*_*eme 18 c++ parsing boost split
我使用boost :: split来解析数据文件.数据文件包含如下行.
data.txt中
1:1~15 ASTKGPSVFPLAPSS SVFPLAPSS -12.6 98.3
Run Code Online (Sandbox Code Playgroud)
项目之间的空白区域是标签.我必须拆分上述代码的代码如下.
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;
Run Code Online (Sandbox Code Playgroud)
对于上面的代码行,我应该得到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
****
Run Code Online (Sandbox Code Playgroud)
Obe*_*ron 17
即使"相邻的分隔符合并在一起",似乎尾随的分隔符也会产生问题,因为即使它们被视为一个,它仍然是一个分隔符.
所以你的问题不能单独解决split().但幸运的是升压字符串ALGO具有trim()和trim_if(),其剥离空格或定界符从开头和一个字符串的结尾.所以只需要调用trim()buf,就像这样:
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;
Run Code Online (Sandbox Code Playgroud)
这个问题已经被问过了:boost :: split在字符串的开头和结尾留下空标记 - 这是理想的行为吗?
我建议使用C++ String Toolkit Library.在我看来,这个库比Boost快得多.我曾经使用Boost来分割(aka 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;
}
Run Code Online (Sandbox Code Playgroud)
---另一个版本
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
}
Run Code Online (Sandbox Code Playgroud)
库的在线文档: String Tokenizer文档 源代码链接:C++ String Toolkit Library
| 归档时间: |
|
| 查看次数: |
20458 次 |
| 最近记录: |