天天看点

Poco::StringTokenizer介绍

工作中经常用到Poco库中的StringTokenizer类,专门查阅了一下类的说明,做了简单总结。

1.基本信息

StringTokenizer类是一个字符串分割类。

库:Foundation;头文件: Poco/StringTokenizer.h

2.构造函数

对字符串的分割功能在类的构造函数中实现:

StringTokenizer(const std::string& str, const std::string& separators, int options = 0);
/// Splits the given string into tokens. The tokens are expected to be
/// separated by one of the separator characters given in separators.
/// Additionally, options can be specified:
///   * TOK_IGNORE_EMPTY: empty tokens are ignored
///   * TOK_TRIM: trailing and leading whitespace is removed from tokens.
           

 参数str为源字符串,separators为分割字符。

options参数取值: 默认为0;TOK_IGNORE_EMPTY,忽略空值;TOK_TRIM,删除首尾空格。

3.数据成员

typedef std::vector < std::string > TokenVec;
TokenVec _tokens;
           

4.接口

成员函数begin(); end(); find();count(); has(); operator[]; replace()

前三个不再赘述(参考vector中的用法),StringTokenizer对象也可以使用迭代器来实现数据访问,但封装的是const迭代器,begin()、end()、find()和迭代器均不可修改数据。

count()函数返回值为_tokens.size();count(const std::string& token)返回数据中与token相等的值的个数。

bool has(const std::string& token) const;
           

若字符串数组中存在与token相同的字符串,则返回true,反之返回false。

std::size_t replace(const std::string& oldToken, const std::string& newToken, std::string::size_type pos = 0);
/// Starting at position pos, replaces all subsequent tokens having value 
/// equal to oldToken with newToken.
/// Returns the number of modified tokens.
           

replace()函数从pos位置开始,将字符数组中与oldToken相同的值替换为newToken,并统计替换个数作为返回值。

operator[]有const和非const两个版本,可以修改数据。

5 简单例子

string strLineData("1,2,3,4,5,1");
Poco::StringTokenizer st(strLineData, ",");
for(size_t i = 0; i < st.count(); i++)
    cout << st[i] << endl;
cout << "数据中有几个1:" << st.count("1") << endl;
//将数据中4替换为2
size_t replaceCnt = st.replace("4", "2");
           

原创博客,转载请注明出处。