strtok()函数解释

#include <string.h>
char *strtok(char *str, const char *delim);
char *strtok_r(char *str, const char *delim, char **saveptr);
功能:分解字符串为一组标记串。str为要分解的字符串,delim为分隔符字符串。
说明:首次调用时,str必须指向要分解的字符串,随后调用要把s设成NULL。
      strtok在str中查找包含在delim中的字符并用NULL('/0')来替换,直到找遍整个字符串。
      返回指向下一个标记串。当没有标记串时则返回空字符NULL。
实例:用strtok来判断ip地址是否合法:ip_strtok.c:

[c-sharp]  view plain copy
  1. //ip_strtok.c  
  2. #include <stdio.h>  
  3. #include <string.h>  
  4. int main(int argc, char **argv)  
  5. {  
  6.    char temp_buf[100] = {};  
  7.    char p_temp[100];  
  8.    char *p=NULL;  
  9.    char *t = ".";  
  10.    int m,n,i;  
  11.    int j=0,s=0;  
  12.      
  13.    if(argc!=2)  
  14.    {  
  15.      printf("param must 2/n");  
  16.      return -1;  
  17.    }  
  18.    strcpy(temp_buf, argv[1]);  
  19.    for(i=0; i<strlen(temp_buf);i++)  
  20.    {   
  21.      if(temp_buf[i] == *t)j++;  
  22.      if(temp_buf[i] == *t && (temp_buf[i+1]>='0'&&temp_buf[i+1]<='9'))  
  23.      {  
  24.        s++;  
  25.      }  
  26.    }  
  27.    if(j!=3 || j!=s)  
  28.    {  
  29.      printf("ip param format error/n");  
  30.      return -1;  
  31.    }  
  32.    p = strtok(temp_buf, t);  
  33.      
  34.    while(p!=NULL)  
  35.    {  
  36.       strcpy(p_temp, p);  
  37.       printf("%s /n", p_temp);  
  38.       for(n=0; n<strlen(p_temp);n++)  
  39.       {  
  40.         if(!(p_temp[n]>='0'&&p_temp[n]<='9'))  
  41.         {  
  42.           printf("ip param error/n");  
  43.           return -1;  
  44.         }  
  45.       }  
  46.         
  47.       m = atoi(p_temp);  
  48.       if(m>255)  
  49.       {  
  50.         printf("ip invalid /n");  
  51.         return -1;  
  52.       }  
  53.         
  54.       p=strtok(NULL, ".");  
  55.       printf("p = %s/n",p);  
  56.    }  
  57.    printf("ok! ip correct! ip=%s/n", argv[1]);  
  58.    return 0;  
  59. }  

编译运行:

[root@localhost liuxltest]# uname -r
2.6.26  
[root@localhost liuxltest]# gcc -Wall ip_strtok.c -o ip_strtok
[root@localhost liuxltest]# ./ip_strtok 172.18.4.255
172 
p = 18
18 
p = 4

p = 255
255 
p = (null)
ok! ip correct! ip=172.18.4.255
[root@localhost liuxltest]# ./ip_strtok 172.18.
ip param format error

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值