标记器点分开,但也保留空字段
Boost::tokenizer point separated, but also keeping empty fields
我看到了这个问题,我的问题和它非常相似,但它是不同的,所以请不要把它标记为重复。
我的问题是:我如何从字符串中获得空字段?
我有一个像std::string s = "This.is..a.test";
这样的字符串,我想得到<This> <is> <> <a> <test>
字段。
我也试过了
typedef boost::char_separator<char> ChSep;
typedef boost::tokenizer<ChSep> TknChSep;
ChSep sep(".", ".", boost::keep_empty_tokens);
TknChSep tok(s, sep);
for (TknChSep::iterator beg = tok.begin(); beg != tok.end(); ++beg)
{
std::cout << "<" << *beg << "> ";
}
但是我得到了<This> <.> <is> <.> <> <.> <a> <test>
Boost的第二个参数。标记器的char_separator
是kept_delims
参数。它用于指定将显示为令牌的分隔符。原始代码指定"."
应该作为令牌保存。要解决这个问题,修改:
ChSep sep(".", ".", boost::keep_empty_tokens);
:
ChSep sep(".", "", boost::keep_empty_tokens);
// ^-- no delimiters will show up as tokens.
下面是一个完整的例子:
#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
int main()
{
std::string str = "This.is..a.test";
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep(
".", // dropped delimiters
"", // kept delimiters
boost::keep_empty_tokens); // empty token policy
BOOST_FOREACH(std::string token, tokenizer(str, sep))
{
std::cout << "<" << token << "> ";
}
std::cout << std::endl;
}
产生期望的输出:
<This> <is> <> <a> <test>
我想我会跳过Boost::tokenizer
,只是使用标准正则表达式来进行拆分:
#include <iterator>
#include <regex>
#include <string>
#include <iostream>
int main() {
std::string s = "This.is..a.test";
std::regex sep{ "\." };
std::copy(std::sregex_token_iterator(s.begin(), s.end(), sep, -1),
std::sregex_token_iterator(),
std::ostream_iterator<std::string>(std::cout, "n"));
}
结果:This
is
a
test
相关文章:
- 将结构字段的类型展开为可变模板参数
- 将位字段导出到数组
- 为了方便起见,我应该避免公开私有字段变量吗
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 在java中读取c++字节的位字段
- 链接器找不到在虚拟类 c++ 中访问的静态字段的符号
- 私有字段对象与私有继承?
- 声明没有默认构造函数的字段
- C++内存模型和位字段的最大序列
- 声明为无效的变量或字段'...' Ardunio 编译器上的错误
- 如何在QByteArray中放置和检索位字段而不会感到痛苦?
- C++ win32 如何使密码字段可选并启用复制和粘贴?
- 如何通过UDP接收QByteArray并将其解析为位字段结构?
- 仅匹配集合中的某些字段
- 结构字段名称与 GDB 中的 STL 数组冲突
- 如何使用位字段将数据从二进制文件复制到结构中?
- 更改保留指向其字段的原始指针的对象地址
- C++:为智能指针的字段隐式保留右值引用
- 设备控制块(DCB)中的fDummy2字段是为什么保留的
- 标记器点分开,但也保留空字段