C++ 标记化字符串 - 不工作

C++ Tokenize String - Not Working

为了在迭代循环中将子字符串添加到向量,我无法标记字符串。

下面有这个。

当我 运行 它时,我从这个函数调用中得到一个 return 值 1,我很确定这是不准确的。

serialized.find_first_of(categoryDelim, outterPrev)

代码

void Serialized::deserialize()
{
        std::string serialized = "-1~-2~BK~123|~me|~you|~us|~9|~stuff|~";
        char categoryDelim = '~';
        char elemDelim = '|';

    if (!serialized.empty())
    {
        //Make sure the container is empty
        innerClear();

        //do the work
        std::vector<std::string>::iterator vecIt;
        std::vector<std::vector<std::string>*>::iterator vecVecIt;

        vecVecIt = vecVec.begin();
        vecIt = (*vecVecIt)->begin();

        //int categoryCount;
        //int elemCount;

        size_t innerPrev = 0;
        size_t innerNext = 0;

        size_t outterPrev = 0;
        size_t outterNext = 0;

        //Check to see whether there is another category delimter after the previous
        while (outterNext = serialized.find_first_of(categoryDelim, outterPrev) != std::string::npos)
        {
            //Check to see whether there are more characters or category delimiters after the previous
            while (innerNext = serialized.find_first_of(elemDelim, innerPrev) != std::string::npos &&
                (serialized.find_first_of(elemDelim, innerPrev)+1 < serialized.find_first_of(categoryDelim, innerPrev)))
            {
                //Add the element to the current inner vector
                (*vecVecIt)->push_back(serialized.substr(innerPrev, (innerNext - innerPrev)));
                innerPrev = innerNext + 1;
            }
            //Advance to the next category delimiter and inner vector
            outterPrev = outterNext + 1;
            vecVecIt++;
        }
    }
}

这是因为你使用了错误的条件:

outterNext = serialized.find_first_of(categoryDelim, outterPrev) != std::string::npos

平均值

outterNext = (serialized.find_first_of(categoryDelim, outterPrev) != std::string::npos)

所以 outterNext = 1serialized.find_first_of(categoryDelim, outterPrev) != std::string::npos

我认为你应该避免这样的代码,它通常会导致很多错误。使您的代码简单,便于阅读和维护。