【问题标题】:What's the best way to split a "," separated list into an array in C. [duplicate]将“,”分隔的列表拆分为C中的数组的最佳方法是什么。 [重复]
【发布时间】:2012-07-16 18:32:24
【问题描述】:

可能重复:
Split string with delimiters in C

在 C 中将“,”分隔的列表拆分为数组的最佳方法是什么。我知道列表中有多少东西。

char list = "one,two,three,four";
int ENTServerAmount = 8;
char **ENTServer;
ENTServer = malloc(sizeof(char *) * ENTServerAmount);
*** Code that splits "list" into "ENTServer" ***

另外我不擅长分配,所以如果我的分配语句有误,请告诉我。

【问题讨论】:

  • 你怎么会得到一个这样初始化的char

标签: c


【解决方案1】:

strtok() 可能就是你要找的函数。

char list[] = "one,two,three,four";
int ENTServerAmount = 8;
char **ENTServer;

char *tmp = strtok (str, ",");

int index = 0;
while (pch != NULL)
{
   ENTSever[index++] = tmp;
   tmp = strtok (NULL, ",");
}

【讨论】:

  • -1 strtok 不好,它不是可重入/多线程安全的,会破坏字符串(字符串不能是 const/literal)并且还会忽略像“,”这样的空字段。最好将 sscanf 与 %n 一起使用。
  • @user411313 对于 OP 解释的简单示例,strtok 是正确的方法。我承认,strtok 有它的缺点,但它简单易懂。由于 OP 对 C 来说似乎是新手,所以不妨先向他介绍简单的东西,以后再介绍更复杂的东西。
猜你喜欢
  • 1970-01-01
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-18
  • 1970-01-01
相关资源
最近更新 更多