从给定的Boost token_iterator中识别原始字符串中的位置

时间:2011-05-02 10:58:04

标签: c++ boost stl tokenize

如果使用Boost标记生成器处理了一个字符串,则可以获取给定标记迭代器指向的原始字符串中的位置:

boost:tokenizer<> tok( "this is the original string" );
for(tokenizer<>::iterator it=tok.begin(); it!=tok.end();++it)
{
    std::string strToken = *it;
    int charPos = it.?                /* IS THERE A METHOD? */
}

我意识到我可以使用已定义的'keep delimiters'列表创建一个特定的char_separator,并指定keep_empty_tokens来尝试跟踪迭代器的进度,但我希望有一种更简单的方法只使用迭代器本身。

3 个答案:

答案 0 :(得分:5)

这似乎是您正在寻找的:

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

int main()
{
  typedef boost::tokenizer<> tok_t;

  std::string const s = "this is the original string";
  tok_t const tok(s);
  for (tok_t::const_iterator it = tok.begin(), it_end = tok.end(); it != it_end; ++it)
  {
    std::string::difference_type const offset = it.base() - s.begin() - it->size();
    std::cout << offset << "\t::\t" << *it << '\n';
  }
}

Online Demo

答案 1 :(得分:1)

如果只需要当前令牌的结尾,base()成员函数 可能符合目的:

std::string s = "this is the original string";
boost::tokenizer<> tok(s);
for(boost::tokenizer<>::iterator it=tok.begin(); it!=tok.end();++it)
{
    int charPos = it.base() - s.begin();
}

不幸的是,似乎没有办法检索开头 boost::tokenizer中的当前令牌。

答案 2 :(得分:0)

怎么样:

 int charPos = it - tok.begin() ;