C++ 字符串拆分错误(复杂方式)

标签 c++ string visual-c++ boost split

我正在尝试通过以下方式在 C++ 中吐出一个字符串:

#include <bitset>
#include <iostream>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/timer.hpp>

using namespace std;
size_t const N = 10000000;

typedef string::const_iterator iter;
typedef boost::iterator_range<iter> string_view;

template<typename C>
void test_custom(string const& s, char const* d, C& ret)
{
    C output;

    bitset<255> delims;
    while (*d)
    {
        unsigned char code = *d++;
        delims[code] = true;
    }
    typedef string::const_iterator iter;
    iter beg;
    bool in_token = false;

    bool go = false;

    for (string::const_iterator it = s.begin(), end = s.end(); it != end; ++it)
    {
        if (delims[*it])
        {
            if (in_token)
            {

                output.push_back(typename C::value_type(beg, it));
                in_token = false;
            }
        }
        else if (!in_token)
        {
            beg = it;
            in_token = true;
        }
        else
        {
            if (!go)
            {
                cout << typename C::value_type(beg, it);
                //outputs the first character
                go = true;
            }
        }
    }

    if (in_token)
        output.push_back(typename C::value_type(beg, s.end()));
    output.swap(ret);
}

vector<string_view> split_string(string in, const char* delim = " ")
{
    vector<string_view> vsv;
    test_custom(in, delim, vsv);

    return vsv;
}

int split()
{
    string text = "123 456";

    vector<string_view> vsv = split_string(text);

    for (int i = 0; i < vsv.size(); i++)
        cout << endl << vsv.at(i) << "|" << endl;

    return 0;
}

这里的问题是第一个字符由于某种原因被删除了......返回的字符串是'23'和'456'但我希望它们是'123 ' 和 '456'

所以,第一个字符是' '而不是'1'

最佳答案

我不熟悉 boost::iterator_range,但它确实听起来像一对迭代器。

如果是这样,那么在这段代码中:

vector<string_view> split_string(string in, const char* delim = " ")
{
    vector<string_view> vsv;
    test_custom(in, delim, vsv);

    return vsv;
}

您返回的迭代器引用了一个名为 in 的本地 string,该字符串在函数返回时已不复存在。

这是未定义的行为。

一个解决方法是通过引用传递该字符串。


顺便说一下,一种在空白处拆分字符串的低效但简单且安全的方法是使用 istringstream:

istringstream stream( source_string );
string word;
while( stream >> word ) { cout << word; }

免责声明:代码未经编译器处理。

关于C++ 字符串拆分错误(复杂方式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20447646/

相关文章:

c++ - 有什么办法可以用模板制作容器模板吗?

c# - 如何将文件中的整个文本连接到字符串中,避免字符串之间出现空行

ruby - 在 Ruby 中的第一个 = 符号之后获取子字符串

c++ - 变量变化值的断点?

c++ - 在类名后使用 MSVCC 扩展关键字 "abstract"是一个好习惯吗?

c - 数组初始化时出现错误 LNK2001 : unresolved external symbol _memset

c++ - 双图插入问题

c++ - 如何检测像素图边缘透明的两个 QGraphicsPixmapItem 之间的碰撞?

c++ - 是否可以在 C++ 的派生类中的特定偏移处附加结构?

c++ - 将字符串格式化为科学记数法