C++ boost拆分字符串

c++ boost split string(C++ boost拆分字符串)

本文介绍了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拆分字符串

基础教程推荐