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拆分字符串
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01