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
這個參數用來存放分隔符(例如:,.!@#$%%^&*() \t \n之類可以區別單詞的符號)
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\tof ,,tokens\nand some more tokens";
char seps[] = " .,\t\n";
char *token = NULL;
char *next_token = NULL;int main(void)
{
printf("Tokens:\n");// 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\n", token);
token = strtok_s(NULL, seps, &next_token);
}
}
printf("the rest token1:\n");
printf("%d", token);
}
環境:VS2013
采用F11逐步調試:
======================================================================================================
當程序運行完17行的語句時值
token的值由A覆蓋NULL
next_token的值由A后其余所有的字符覆蓋了NULL
因此token!=NULL
符合進入While語句的條件、
當程序進入whlie語句運行完24行時
token的值被覆蓋為string
next_token的值被覆蓋為string后的字符串
經過幾次循環之后
token中的值變為NULL
next_token中的值為空被取時,會被函數去掉末尾的\0(由雙引號加上去的)//tips:給數組賦值時,雙引號是初始化,初始化會在末尾加一個\0所以給一個數組初始化時\0會占一個字節,花括號是賦值不會占一個字節