将逗号分隔的字符串转换为proc中的数组

时间:2015-06-15 09:06:03

标签: c string split

我需要将逗号分隔的字符串转换为proc中的数组,我得到的字符串是:

while ((ch = getopt(argc, argv, "do:c")) != EOF)
{
    switch (ch) 
    {
        case 'c':
            get_order_type(optarg);

get_order_type(optarg)是逗号分隔的字符串,如30,31,32我需要获取每个字符串。

2 个答案:

答案 0 :(得分:1)

您正在寻找的功能是strtok。这意味着String Tokenizer。

我认为这对你有用:

  char str[] = get_order_type(optarg);
   const char s[2] = ",";
   char *token;

   /* get the first token */
   token = strtok(str, s);

   /* walk through other tokens */
   while( token != NULL ) 
   {
      printf( " %s\n", token );

      token = strtok(NULL, s);
   }

无论如何,here您拥有该方法的文档。

希望它有所帮助!!

答案 1 :(得分:0)

#define max_strln 30

#define max_str_no 20

char input[] = get_order_type(optarg);
char *str;
int i_ctr;
char arr[max_str_no ][max_strln];    

for(i_ctr = 0,str = strtok(input,","); str!= NULL; i_ctr++, str= strtok(NULL,","))
  {
    strcpy( arr[i_ctr], str);
  }

说明:

我们在“input”变量中使用逗号分隔符字符串,并通过分隔符(此处为逗号)对该变量进行标记。 strtok返回字符串,它由分隔符分隔(此处逗号为分隔符)。 最后我们使用复制功能将该字符串复制到数组中。