C语言strtok_s函数

strtok_s 在C语言中的作用是分割出一个字符串中的单词

在MSDN上参数表:

strtok_s

strToken String containing token or tokens.
strDelimit Set of delimiter characters.
context Used to store position information between calls to strtok_s
locale Locale to use.

4个参数的含义:

strToken

这个参数用来存放需要分割的字符或者字符串整体

strDelimit

这个参数用来存放分隔符(例如:,.!@#$%%^&*() 之类可以区别单词的符号)

context

这个参数用来存放被分割过的字符串

locale

这个参数用来储存使用的地址

//虽说有4个参数,但是我们可控参数只有3个locale是不可控的

remark:

与这个函数相近的函数:

wcstok_s 宽字节版的strtok_s

_mbstok_s 多字节版的strtok_S

===============================================================================================================================================

接下来我们来看这个函数的运行过程:

在首次调用strtok_s这个功能时候会将开头的分隔符跳过然后返回一个指针指向strToken中的第一个单词,在这个单词后面茶插入一个NULL表示断开。多次调用可能会使这个函数出错,context这个指针一直会跟踪将会被读取的字符串。

跟踪以下代码中的参数来更好的理解这个函数:

#include <string.h>
#include <stdio.h>

char string[] =
".A string of ,,tokens and some  more tokens";
char seps[] = " ., ";
char *token = NULL;
char *next_token = NULL;

int main(void)
{
    printf("Tokens: ");

    // Establish string and get the first token:
    token = strtok_s(string, seps, &next_token);

    // While there are tokens in "string1" or "string2"
    while (token != NULL)
    {
        // Get next token:
        if (token != NULL)
        {
            printf(" %s ", token);
            token = strtok_s(NULL, seps, &next_token);
        }
    }
    printf("the rest token1: ");
    printf("%d", token);
}

环境:VS2013

采用F11逐步调试:

======================================================================================================

image

当程序运行完17行的语句时值

token的值由A覆盖NULL

next_token的值由A后其余所有的字符覆盖了NULL

因此token!=NULL

符合进入While语句的条件、

当程序进入whlie语句运行完24行时

image

token的值被覆盖为string

next_token的值被覆盖为string后的字符串

经过几次循环之后

token中的值变为NULL

next_token中的值为空被取时,会被函数去掉末尾的(由双引号加上去的)//tips:给数组赋值时,双引号是初始化,初始化会在末尾加一个所以给一个数组初始化时会占一个字节,花括号是赋值不会占一个字节

image

原文地址:https://www.cnblogs.com/luverose/p/4248992.html