c++ boost split string(C++ boost拆分字符串)
问题描述
我正在使用 boost::split 方法将字符串拆分为:
I'm using the boost::split method to split a string as this:
我首先确保包含正确的标头以访问boost::split:
I first make sure to include the correct header to have access to boost::split:
#include <boost/algorithm/string.hpp>
然后:
vector<string> strs;
boost::split(strs,line,boost::is_any_of(" "));
线条就像
"test test2 test3"
这就是我使用结果字符串向量的方式:
This is how I consume the result string vector:
void printstrs(vector<string> strs)
{
for(vector<string>::iterator it = strs.begin();it!=strs.end();++it)
{
cout << *it << "-------";
}
cout << endl;
}
但是为什么结果strs我只得到"test2"和"test3",不应该是"test"、"test2" 和"test3",字符串中有 (制表符).
But why in the result strs I only get "test2" and "test3", shouldn't be "test", "test2" and "test3", there are (tab) in the string.
2011 年 4 月 24 日更新: 我在 printstrs 处更改了一行代码后,似乎可以看到第一个字符串.我改变了
Updated Apr 24th, 2011: It seemed after I changed one line of code at printstrs I can see the first string. I changed
cout << *it << "-------";
到
cout << *it << endl;
而且似乎 "-------" 以某种方式覆盖了第一个字符串.
And it seemed "-------" covered the first string somehow.
推荐答案
问题出在您代码的其他地方,因为它有效:
The problem is somewhere else in your code, because this works:
string line("test test2 test3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of(" "));
cout << "* size of the vector: " << strs.size() << endl;
for (size_t i = 0; i < strs.size(); i++)
cout << strs[i] << endl;
并测试您的方法,它使用向量迭代器也有效:
and testing your approach, which uses a vector iterator also works:
string line("test test2 test3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of(" "));
cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
cout << *it << endl;
}
同样,您的问题出在其他地方.也许您认为字符串中的 字符不是.我会用调试填充代码,首先监视向量上的插入,以确保所有内容都按预期插入.
Again, your problem is somewhere else. Maybe what you think is a character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.
输出:
* size of the vector: 3
test
test2
test3
这篇关于C++ boost拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ boost拆分字符串
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
