使用 C++ boost::split 拆分字符串,而不在引号文本内拆分
Split a string using C++ boost::split without splitting inside quoted text
我正在使用
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_namefirst_argument第二个参数是带引号的字符串。
请参阅 https://ideone.com/gwCpug 的演示。
我不确定这个解决方案是可移植的(我们违反了 bool operator() (char ch) const
的 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
相关文章:
- 文本文件中的单词链表
- 将英文文本拆分为多个行
- 如何在Qt文本阅读中拆分t
- 如何使用 c++ 逐行处理文本文件并将其参数拆分为变量?
- 如何将文本(诗歌)拆分为行(字符串/字符[])并查找每个行的最后一个单词
- 使用 C++ boost::split 拆分字符串,而不在引号文本内拆分
- 分析示例文本文件并将其拆分
- 如何将XML文件拆分为多个XML,以便每个新文件只包含原始文件中的一个文本节点
- 正在分析文本文件并从中拆分
- 拆分和合并文本
- 将文本输入中的字符串拆分为更小的字符串
- c++如何将文本文件中的一行拆分为两行,然后将每行存储到两个不同的数组中
- 将大型数据文件拆分为多个小文件(文本格式)
- 将文本文件拆分为多个文件 c++
- 通过使用分隔符C++拆分文本来制作 2D 数组
- 将单独文本文件的段落拆分为单独的字符串
- 当找到某个令牌时,是否有更快的方法来拆分文本文件
- 如何从文本文件中读取并在C中拆分句子
- 使用正则表达式在Embarcadero的C++生成器中将文本拆分为单个单词
- 使用ICU将文本拆分为单词列表