如何忽略字符串中字符后的所有内容?

时间:2019-05-11 07:48:23

标签: c++ string shell token strtok

我正在尝试在C ++中修改strtok()函数,如果在char指针遍历字符串的过程中到达“#”字符,则忽略该字符之后的所有内容,并且该函数不再返回任何内容。在我的代码中,我包含了额外的if语句,如果char指针到达'#'字符,则返回它之前的所有内容,并使用break语句终止该过程。布尔变量还用于控制主函数中的循环,因此,如果更改其值将防止无限循环。

但是,代码仍然导致无限循环,我的思考过程也是如此。

#include <iostream>
#include <string>

using namespace std;
char *userdefine_strtok(char *arg, string delimiter, bool &breaker)
{
    static int pos = 0;
    static char* buf = 0;
    static char* token = 0;

    if (arg)
    {
        //start a new search
        pos = 0;
        buf = arg;

        //delete previous token if any
        if (token) delete token;

        //create token at least as big as the argument
        token = new char[strlen(buf) + 1];
    }

    if (!buf)
        return 0;

    if (pos >= strlen(buf))
        return 0;

    //prepare the token
    memset(token, 0, strlen(buf) + 1);

    int i = 0;
    while (pos < strlen(buf))
    {
        for (int j = 0; j < delimiter.length(); j++) {
        if (buf[pos] == delimiter[j])
        {
            pos++;
            return token;
        }

        }

        if (buf[pos] == '#')
        {
            return token; //return everything before character
            breaker = false; //bool is false so while loop in main will not continue
            break;//break out of the current loop
        }

        token[i] = buf[pos];
        i++;
        pos++;


    }

    return token;
}

int main()
{
    bool stopper = true;
    char *buf = "hello,world#1a,2!b,3c";
    cout << "String is :" << buf << endl << endl;
    char *token = userdefine_strtok(buf, ",!", stopper);
    while (token && stopper)
    {
        std::cout << token << "\n";
        token = userdefine_strtok(NULL, ",!", stopper);

    }


    system("PAUSE");
    return 0;
}


1 个答案:

答案 0 :(得分:0)

    if (buf[pos] == '#')
    {
        return token; //return everything before character
        breaker = false; //bool is false so while loop in main will not continue
        break;//break out of the current loop
    }

return语句之后的所有内容都将被忽略,因此您需要像这样安排它:

    if (buf[pos] == '#')
    {
        breaker = false; //bool is false so while loop in main will not continue
        return token; //return everything before character
        //break; This line is useless.
    }