常见 strtok函数的使用之处是在点分十进制的ip地址提取中,本文是通过简单的例子将点分十进制的ip地址转化为数字。
函数原型:char *strtok(char s[], const char *delim);
首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。
is NULL, the saved pointer in SAVE_PTR is used as the next starting point. ” 翻译成汉语就是:作用于字符串s,以包含在delim中的字符
为分界符,将s切分成一个个子串;如果,s为空值NULL,则函数保存的指针SAVE_PTR在下一次调用中将作为起始位置。
代码如下:
#include<stdio.h>
#include<string.h>
int main(void)
{
char str[]="192.168.12.113";
char *p=NULL;
int arr[4];
int i=0;
p=strtok(str,".");
for(i=0;i<4;i++)
{
if( p == NULL)
{
arr[i]=0;
return ;
}
else
{
arr[i]=atoi(p);
printf("%d\n",arr[i]);
}
p=strtok(NULL,".");
}
return 0;
}
输出结果:
192
168
12
113
以上就是strtok函数的简单使用。