函数strtok

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:

// Program to check if a given string is valid IPv4 address or not
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define DELIM "."
 
/* return 1 if string contain only digits, else return 0 */
int valid_digit(char *ip_str)
{
    while (*ip_str) {
        if (*ip_str >= '0' && *ip_str <= '9')
            ++ip_str;
        else
            return 0;
    }
    return 1;
}
 
/* return 1 if IP string is valid, else return 0 */
int is_valid_ip(char * ip_str)
{
    int i, num, dots = 0;
    char *ptr;

	if(ip_str == NULL)
		return 0;

	char *tmpstr = (char *)malloc(sizeof(ip_str));
	memset(tmpstr, 0, sizeof(ip_str));
 
    if (ip_str == NULL){
		free(tmpstr);
        return 0;
	}
 
    // See following link for strtok()
    // http://pubs.opengroup.org/onlinepubs/009695399/functions/strtok_r.html
    ptr = strtok(tmpstr, DELIM);
 
    if (ptr == NULL){
		free(tmpstr);
        return 0;
	}
 
    while (ptr) {
 
        /* after parsing string, it must contain only digits */
        if (!valid_digit(ptr)){
			free(tmpstr);
            return 0;
		}
 
        num = atoi(ptr);
 
        /* check for valid IP */
        if (num >= 0 && num <= 255) {
            /* parse remaining string */
            ptr = strtok(NULL, DELIM);
            if (ptr != NULL)
                ++dots;
        } else{
			free(tmpstr);
            return 0;
		}
    }
 
    /* valid IP string must contain 3 dots */
    if (dots != 3){
		free(tmpstr);
        return 0;
	}


	free(tmpstr);
    return 1;
}
 
// Driver program to test above functions
int main()
{
    char ip1[] = "128.0.0.1";
    char ip2[] = "125.16.100.1";
    char ip3[] = "125.512.100.1";
    char ip4[] = "125.512.100.abc";
    is_valid_ip(ip1)? printf("Valid
"): printf("Not valid
");
    is_valid_ip(ip2)? printf("Valid
"): printf("Not valid
");
    is_valid_ip(ip3)? printf("Valid
"): printf("Not valid
");
    is_valid_ip(ip4)? printf("Valid
"): printf("Not valid
");
	
	printf("ip4 is %s
", ip4);
    return 0;
}

参考:

1、关于函数strtok和strtok_r的使用要点和实现原理(二)

原文地址:https://www.cnblogs.com/xuanyuanchen/p/5952860.html