用strtok函数将ip地址转化为数字

来源:互联网 发布:windows 设置闹钟 编辑:程序博客网 时间:2024/04/27 19:17

        常见 strtok函数的使用之处是在点分十进制的ip地址提取中,本文是通过简单的例子将点分十进制的ip地址转化为数字。

函数原型:char *strtok(char s[], const char *delim);


功能作用:分解字符串为一组字符串。s为要分解的字符,delim为分隔符字符(如果传入字符串,则传入的字符串中每个字符均为分割符)。

首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。


内核中的解释:strtok的函数原型为char *strtok(char *s, char *delim),功能为“Parse S into tokens separated by characters in DELIM.If S
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函数的简单使用。



0 1
原创粉丝点击