我正在使用
boost::split(strs, r_strCommandLine, boost::is_any_of("\t "));
将字符串吐出到 token 中以解析简单的脚本。到目前为止,一切都很好。但是,对于下面的字符串
command_name first_argument "Second argument which is a quoted string."
我希望我的代币是
strs[0] = command_name
strs[1] = first_argument
strs[2] = "Second argument which is a quoted string."
当然,我可以在标记的开头和结尾搜索引号字符,并使用“”合并分隔以引号开头的标记和以引号结尾的标记出现之间的标记,以重新创建引用的字符串,但是我想知道是否有更有效/更优雅的方式来做到这一点。有什么想法吗?
最佳答案
示例使用 boost::tokenizer
:
#include <string>
#include <iostream>
using std::cout;
using std::string;
#include <boost/tokenizer.hpp>
using boost::tokenizer;
using boost::escaped_list_separator;
typedef tokenizer<escaped_list_separator<char> > so_tokenizer;
int main()
{
string s("command_name first_argument "
"\"Second argument which is a quoted string.\"");
so_tokenizer tok(s, escaped_list_separator<char>('\\', ' ', '\"'));
for(so_tokenizer::iterator beg=tok.begin(); beg!=tok.end(); ++beg)
{
cout << *beg << "\n";
}
return 0;
}
输出:
command_name first_argument Second argument which is a quoted string.
参见 https://ideone.com/gwCpug 的演示.
关于c++ - 使用 C++ boost::split 拆分字符串而不拆分引用文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13406387/