C++使用boost对字符串进行标记化,并将标记保存为字符串
C++ tokenize a string with boost and save a token as a string
我需要将一个字符串拆分为多个令牌,并将第三个令牌作为字符串返回。
我有以下代码:
#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';
}
}
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- C++.我想将更改后的特定字符行保存在字符串中
- 保存名称或字符串
- C++ 将地址保存为字符串的向量转换为新的向量
- C++读取大文件并将其保存到字符串中,然后删除特定的随机单词
- C++以尽可能快的速度逐行将字符串保存到文件中
- 如何在c++中将字符串中的所有数字保存到多维数组中
- 如何将字符串保存在最长的常见子序列递归算法中
- 如果我不将预先编写的字符串保存到变量,它还在内存中吗?
- 仅将纪元字符串保存到 mysql 日期时间年/月/日,但没有小时分钟秒
- 将字符串保存在集合中时,C_STR()仍然有效
- 分类一个向量,该向量由该类中的成员字符串保存对象
- 如何拆分 QString 并将一部分字符串保存在浮点数的向量中
- 为什么第二个字符串保存在第一个字符串中
- C++ 如何将 argv 作为字符串保存到矢量
- 在C++中使用字符指针将字符串保存到类属性
- 如何将字符串保存为二进制文件
- 将字符串保存到重载括号中,不改变对象的字段
- 如何在标记后将字符串保存在数组中
- 我如何将base64字符串保存为Qt中的png图像