標籤:
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
這個參數用來存放分隔字元(例如:,[email protected]#$%%^&*() \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會佔一個位元組,花括弧是賦值不會佔一個位元組
C中的strtok_s函數小探索