字符串格式 “123,345,124,1234,123,4”
分割解析 成 123 345 124 1234 123 4
动态开辟空间
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char **name = NULL;
//获取字符串个数
int get_extend_code_num(char * str)
{
int len = strlen(str);
char comma = ',';
int i= 0;
int count = 1;
while(i < len){
if(str[i] == comma){
count++;
}
i++;
}
return count;
}
int get_extend_code(char *str,int num ,char **test)
{
const char s[2] = ",";
char *token;
int i = 0;
/* 获取第一个子字符串 */
token = strtok(str, s);
/* 继续获取其他的子字符串 */
while( token != NULL ) {
test[i] = (char*)malloc(strlen(token)+1);
strcpy(test[i],token);
printf( "%s\n", token );
token = strtok(NULL, s);
i++;
}
return 0;
}
void name_free(char** test,int num)
{
int i = 0;
for(;i<num;i++){
free(test[i]);
}
free(test);
}
int main()
{
char test1[] = "123,345,124,1234,123,4";
int num = get_extend_code_num(test1);
printf("%s has %d str\n",test1,num);
char*** test = &name;
*test = calloc(num,sizeof(char*));
get_extend_code(test1,num,*test);
int i = 0;
while(i<num){
printf("%s ",name[i]);
i++;
}
printf("\n");
name_free(*test,num);
return 0;
}
效果