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?
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.
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.
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.
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.
man sscanf:
[
Matches a nonempty sequence of characters from the specified set of accepted characters;
(emphasis added).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With