简体   繁体   English

C ++ Tokenize字符串 - 不工作

[英]C++ Tokenize String - Not Working

I am having trouble tokenizing a string in order to add the substrings to vectors in an iterative loop. 我无法对字符串进行标记,以便在迭代循环中将子字符串添加到向量中。

I have this below. 我在下面有这个。

When I run it, I am getting a return value of 1 from this function call, which I'm pretty sure is not accurate. 当我运行它时,我从这个函数调用得到一个返回值1,我很确定这是不准确的。

serialized.find_first_of(categoryDelim, outterPrev)

Code

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++;
        }
    }
}

This is because you use wrong condition: 这是因为你使用了错误的条件:

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

mean 意思

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

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

I think you should avoid codes like that, it's often cause of many error. 我认为你应该避免这样的代码,这通常会导致许多错误。 Make your code simple, it's good for read and maintain. 使您的代码简单,有利于阅读和维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM