今天寫了 strtok 的範例:『如何分離網路 mac address』程式碼如下,大家一定會有疑問 strtok 第一次呼叫,第一參數輸入愈分離的字串,在 while 迴圈,則是輸入 NULL 呢?底下就來解析 strtok.c 的程式碼。
/*
*
* Author : appleboy
* Date : 2010.04.01
* Filename : strtok.c
*
*/
#include “string.h”
#include “stdlib.h”
#include “stdio.h”
int main()
{
char str[]=”00:22:33:4B:55:5A”;
char *delim = “:”;
char * pch;
printf (“Splitting string “%s” into tokens:n”,str);
pch = strtok(str,delim);
while (pch != NULL)
{
printf (“%sn”,pch);
pch = strtok (NULL, delim);
}
system(“pause”);
return 0;
}
*
* Author : appleboy
* Date : 2010.04.01
* Filename : strtok.c
*
*/
#include “string.h”
#include “stdlib.h”
#include “stdio.h”
int main()
{
char str[]=”00:22:33:4B:55:5A”;
char *delim = “:”;
char * pch;
printf (“Splitting string “%s” into tokens:n”,str);
pch = strtok(str,delim);
while (pch != NULL)
{
printf (“%sn”,pch);
pch = strtok (NULL, delim);
}
system(“pause”);
return 0;
}
__strtok_r(char *s, const char *delim, char **last)
{
char *spanp, *tok;
int c, sc;
if (s == NULL && (s = *last) == NULL)
return (NULL);
/*
* Skip (span) leading delimiters (s += strspn(s, delim), sort of).
*/
cont:
c = *s++;
for (spanp = (char *)delim; (sc = *spanp++) != 0;) {
if (c == sc)
goto cont;
}
if (c == 0) { /* no non-delimiter characters */
*last = NULL;
return (NULL);
}
tok = s – 1;
/*
* Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
* Note that delim must have one NUL; we stop if we see that, too.
*/
for (;;) {
c = *s++;
spanp = (char *)delim;
do {
if ((sc = *spanp++) == c) {
if (c == 0)
s = NULL;
else
s[-1] = ‘
{
char *spanp, *tok;
int c, sc;
if (s == NULL && (s = *last) == NULL)
return (NULL);
/*
* Skip (span) leading delimiters (s += strspn(s, delim), sort of).
*/
cont:
c = *s++;
for (spanp = (char *)delim; (sc = *spanp++) != 0;) {
if (c == sc)
goto cont;
}
if (c == 0) { /* no non-delimiter characters */
*last = NULL;
return (NULL);
}
tok = s – 1;
/*
* Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
* Note that delim must have one NUL; we stop if we see that, too.
*/
for (;;) {
c = *s++;
spanp = (char *)delim;
do {
if ((sc = *spanp++) == c) {
if (c == 0)
s = NULL;
else
s[-1] = ‘