How does strtok() split the string into tokens in C?

前端 未结 15 1886
陌清茗
陌清茗 2020-11-22 14:48

Please explain to me the working of strtok() function. The manual says it breaks the string into tokens. I am unable to understand from the manual what it actua

15条回答
  •  逝去的感伤
    2020-11-22 15:41

    strtok will tokenize a string i.e. convert it into a series of substrings.

    It does that by searching for delimiters that separate these tokens (or substrings). And you specify the delimiters. In your case, you want ' ' or ',' or '.' or '-' to be the delimiter.

    The programming model to extract these tokens is that you hand strtok your main string and the set of delimiters. Then you call it repeatedly, and each time strtok will return the next token it finds. Till it reaches the end of the main string, when it returns a null. Another rule is that you pass the string in only the first time, and NULL for the subsequent times. This is a way to tell strtok if you are starting a new session of tokenizing with a new string, or you are retrieving tokens from a previous tokenizing session. Note that strtok remembers its state for the tokenizing session. And for this reason it is not reentrant or thread safe (you should be using strtok_r instead). Another thing to know is that it actually modifies the original string. It writes '\0' for teh delimiters that it finds.

    One way to invoke strtok, succintly, is as follows:

    char str[] = "this, is the string - I want to parse";
    char delim[] = " ,-";
    char* token;
    
    for (token = strtok(str, delim); token; token = strtok(NULL, delim))
    {
        printf("token=%s\n", token);
    }
    

    Result:

    this
    is
    the
    string
    I
    want
    to
    parse
    

提交回复
热议问题