C++使用boost对字符串进行标记化,并将标记保存为字符串

C++ tokenize a string with boost and save a token as a string

本文关键字:字符串 保存 使用 boost C++      更新时间:2023-10-16

我需要将一个字符串拆分为多个令牌,并将第三个令牌作为字符串返回。

我有以下代码:

    #include <iostream>
    #include <string>
    #include <cstring>
    #include <boost/tokenizer.hpp>
    #include <fstream>
    #include <sstream>
    using namespace std;
    main()
    {
           std::string line = "Data1|Data2|Data3|Data4|Data5"; 
           typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
           boost::char_separator<char> sep("|");
           tokenizer tokens(line, sep);
           for (tokenizer::iterator tok_iter = tokens.begin();
                    tok_iter != tokens.end(); ++tok_iter)
           std::cout << *tok_iter << endl;
           std::cout << "n";
      }

代码很好地将字符串分隔为标记。现在我不知道如何将第三个令牌保存为一个单独的字符串。

谢谢!

当您知道这是循环的第三次迭代时,只需存储到字符串中。借助std::distance,您不需要任何额外的变量。

   string str;
   for (tokenizer::iterator tok_iter = tokens.begin();
      tok_iter != tokens.end(); ++tok_iter)
   {
      // if it's the 3rd token
      if (distance(tokens.begin(), tok_iter) == 2)
      {
         str = *tok_iter;
         // prints "Data3"
         cout << str << 'n';
      }
   }