1 #include <io_utils.h> 2 #include <string.h> 3 #include <stdlib.h> 4 5 int main() { 6 char string[] = "C, 1972; C++, 1983; Java, 1995; Rust, 2010; Kotlin, 2011"; 7 8 typedef struct { 9 char *name; 10 int year; 11 } Language; 12 13 const char *language_break = ";"; 14 const char *field_break = ","; 15 16 int language_capacity = 3; 17 int language_size = 0; 18 19 Language *languages = malloc(sizeof(Language) * language_capacity); 20 if (!languages) { 21 abort(); 22 } 23 24 char *next = strtok(string, field_break); 25 while (next) { 26 Language language; 27 language.name = next; 28 29 next = strtok(NULL, language_break); 30 if (next) { 31 language.year = atoi(next); 32 33 if(language_size + 1 >= language_capacity) { 34 language_capacity *= 2; 35 languages = realloc(languages, sizeof(Language) * language_capacity); 36 if (!languages) { 37 abort(); 38 } 39 } 40 41 languages[language_size++] = language; 42 43 next = strtok(NULL, field_break); 44 } 45 } 46 47 PRINTLNF("languages: %d", language_size); 48 PRINTLNF("languages capacity: %d", language_capacity); 49 50 for (int i = 0; i < language_size; ++i) { 51 PRINTLNF("Language[name=%s, year=%d]", languages[i].name, languages[i].year); 52 } 53 54 free(languages); 55 56 return 0; 57 }View Code
标签:break,capacity,Language,language,C语言,languages,拆分,字符串,next From: https://www.cnblogs.com/liumy/p/17112656.html