Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse out the fields in a comma separated string using sscanf while supporting empty fields?

I have a comma separated string which might contain empty fields. For example:

1,2,,4

Using a basic

sscanf(string,"%[^,],%[^,],%[^,],%[^,],%[^,]", &val1, &val2, &val3, &val4);

I get all the values prior to the empty field, and unexpected results from the empty field onwards.

When I remove the expression for the empty field from the sscanf(),

sscanf(string,"%[^,],%[^,],,%[^,],%[^,]", &val1, &val2, &val3, &val4);

everything works out fine.

Since I don't know when I'm going to get an empty field, is there a way to rewrite the expression to handle empty fields elegantly?

like image 459
Belrog Avatar asked Oct 02 '09 10:10

Belrog


People also ask

How do you parse a comma separated string?

In order to parse a comma-delimited String, you can just provide a "," as a delimiter and it will return an array of String containing individual values. The split() function internally uses Java's regular expression API (java. util. regex) to do its job.

What method would you use to divide a string of data delimited by a comma into an array of data?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How can you convert comma separated values into an array?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.


2 Answers

If you use strtok with the comma as your separator character you'll get a list of strings one or more of which will be null/zero length.

Have a look at my answer here for more information.

like image 63
ChrisF Avatar answered Sep 28 '22 13:09

ChrisF


man sscanf:

[ Matches a nonempty sequence of characters from the specified set of accepted characters;

(emphasis added).

like image 31
Sinan Ünür Avatar answered Sep 28 '22 12:09

Sinan Ünür