我在用
boost::split(strs, r_strCommandLine, boost::is_any_of("\t "));
吐字符串转换成令牌解析一个简单的脚本。 到现在为止还挺好。 但是,下面的字符串
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 。
我不知道,这个解决方案是便携式(我们违反了常量条件bool operator() (char ch) const
),但它的作品。
该解决方案在理论上是有趣的,我不会在真实的项目中使用它。
#include <boost/algorithm/string/split.hpp>
#include <string>
#include <vector>
#include <iostream>
class split_q {
public:
split_q() : in_q(false) {}
bool operator() (char ch) const
{
if (ch == '\"') in_q = !in_q;
return !in_q && ch == ' ';
}
private:
mutable bool in_q;
};
int main(int argc, char* argv[])
{
std::string in = "command_name first_argument \"Second argument which is a quoted string.\" additional_argument";
std::vector<std::string> res;
boost::algorithm::split(res, in, split_q());
for (size_t i = 0; i < res.size(); ++i)
std::cout << res[i] << std::endl;
return 0;
}
结果:
command_name
first_argument
"Second argument which is a quoted string."
additional_argument