0
0

How to parse a comma separated list

Posted on 2007-12-10 14:48:35 UTC.

I came up with something in my experiments where I needed to parse a comma separated list to vector of floats.
I googled the Internet and found more examples for other languages than for C (there are numerous examples around and mine may not be the best one), but I decided that maybe I’ll put the C how-to to my blog since there are number of places where you could need it, for example when writing some application for Maemo. For example if you have your configuration in an XML-file and want to describe RGBA -color in Cairo compatible format, for example you have this inside mycolor-tag:

1, 0.6, 1, 0.7

You can obtain the mycolor-tag from the xml file with libxml2 with ease (and there is tons of documentation and examples how to use libxml2, for example my and Kate’s EFIS -project uses it to parse configuration files, if you want know how to do that, please go to the Katix EFIS project page on garage.maemo.org and have a look), but now I’ll tell you one way how to get the numbers. Here is one way to do it:

Little example:

char *csv="1, 0.6, 1, 0.7";
double mycolor[4];
...
parse_csvf(csv, 4, mycolor);
...

And then the parsing can then be done as follows:

void parse_csvf(char *csv, int len, double *list){
  int place=0;
  int slen = strlen(csv);
  int i;
  int itemcounter=0;
  char item[255]={0};
  int overflow=0;
  double fitem=0;
	
  for( i=0;i<slen ;i++ ){
    if ( csv[i]>='0' && csv[i]<='9' || csv[i]=='.' ){
      item[itemcounter++]=csv[i];
    } else if ( csv[i]==',' ){
      fitem=0;
      item[itemcounter++]=0;
      fitem = atof( item );
      list[place++]=fitem;
      if( place>=len ) {
        overflow=1;
        break;
      }
      item[0]=0;
      itemcounter=0;
    }
  }
  if(overflow==0){
    item[itemcounter++]=0;
    fitem = atof(item);
    list[place++]=fitem;
  }
}

You could maybe use some helper function from some higher level library, but here is one way how to do it. And you might also end up with a lot cleaner-looking solution if you used C++. However, this is C and many Maemo-programs are written in C. My older C-versions used more than one for-loop, this does the parsing in single pass and might be faster.

Back