现在的位置: 首页 > 综合 > 正文

boost之Tokenizer

2018年02月16日 ⁄ 综合 ⁄ 共 1597字 ⁄ 字号 评论关闭

boost Tokenizer 包提供了灵活和易用的方法来将一个字符串或其它字符序列分解成一系列单词。下面是一个简单的例子,将一个短语分解为单词。

// simple_example_1.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>

int main()
{
	using namespace std;
	using namespace boost;
	string s = "This is,  a test";
	tokenizer<> tok(s);
	for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg)
	{
		cout << *beg << "\n";
	}
}

<me>

结果:

This

is

a

test

</me>

你可以通过指定 TokenizerFunction 来选择如何分解字符串。如果你不指定,则缺省的 TokenizerFunction 是 char_delimiters_separator<char>,它的缺省行为是以空格和标点来分解字符串。这里有一个例子使用了另一个名 为 escaped_list_separator 的 TokenizerFunction. 这个 TokenizerFunction 用于分析一个逗号分隔格式(csv)行的超集。该格式如下例:

Field 1,"putting quotes around fields, allows commas",Field 3

以下例子将上述行分解为3个域。

// simple_example_2.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>

int main()
{
	using namespace std;
	using namespace boost;
	string s = "Field 1,\"putting quotes around fields, allows commas\",Field 3";
	tokenizer<escaped_list_separator<char> > tok(s);
	for(tokenizer<escaped_list_separator<char> >::iterator beg=tok.begin(); beg!=tok.end();++beg)
	{
		cout << *beg << "\n";
	}
}

<me>

结果:

Field 1

putting quotes around fields, allows commas

Field 3

</me>

最后,对于某些 TokenizerFunctions 你必须传入一些东西给它的构造函数,来做一些有趣的事情。一个例子是 offset_separator. 这个类基于偏移量来分解字符串,例如:

用偏移量 2,2,4 来分解 12252001 将产生 12 25 2001. 下面就是这个分解的例子。

// simple_example_3.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>

int main()
{
	using namespace std;
	using namespace boost;
	string s = "12252001";
	int offsets[] = {2,2,4};
	offset_separator f(offsets, offsets+3);
	tokenizer<offset_separator> tok(s,f);
	for(tokenizer<offset_separator>::iterator beg=tok.begin(); beg!=tok.end();++beg)
	{
		cout << *beg << "\n";
	}
}

<me>

结果:

12

25

2001

</me>

【上篇】
【下篇】

抱歉!评论已关闭.