1. strtok
问题背景: 解析形如 “1,2,3,4,5”字符串到整数数组
(1)计算个数
char* delim = ",";
int count = 0;
int *numbers = NULL;
char* str = "1,2,3,4,5";
char* token = strtok(str,delim);
while(token){
count++;
token = strtok(NULL, delim);
}
(2)申请内存,记录数字
numbers = (int*)malloc(sizeof(int)*count);
token = strtok(str, delim);
int index = 0;
while(token){
numbers[index++] = atoi(token);
token = strtok(NULL, delim);
}
问题记录:strtok()函数修改了str字符串本身,所有逗号被改成了‘