1. 程式人生 > >用strtok函式將ip地址轉化為數字

用strtok函式將ip地址轉化為數字

        常見 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函式的簡單使用。