How do I write a function to split and return an array for a string with delimiters in the C programming language?
char* str = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
str_split(str,',');
How do I write a function to split and return an array for a string with delimiters in the C programming language?
char* str = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
str_split(str,',');
This optimized method create (or update an existing) array of pointers in *result and returns the number of elements in *count.
Use "max" to indicate the maximum number of strings you expect (when you specify an existing array or any other reaseon), else set it to 0
To compare against a list of delimiters, define delim as a char* and replace the line:
with the two following lines:
Enjoy
Usage example:
My approach is to scan the string and let the pointers point to every character after the deliminators(and the first character), at the same time assign the appearances of deliminator in string to '\0'.
First make a copy of original string(since it's constant), then get the number of splits by scan it pass it to pointer parameter len. After that, point the first result pointer to the copy string pointer, then scan the copy string: once encounter a deliminator, assign it to '\0' thus the previous result string is terminated, and point the next result string pointer to the next character pointer.
I think the following solution is ideal:
Explanation of the code:
token
to store the address and lengths of the tokensstr
is made up entirely of separators so there arestrlen(str) + 1
tokens, all of them empty stringsstr
recording the address and length of every tokenNULL
sentinel valuememcpy
as it's faster thanstrcpy
and we know the lengthsNote
malloc
checking omitted for brevity.In general, I wouldn't return an array of
char *
pointers from a split function like this as it places a lot of responsibility on the caller to free them correctly. An interface I prefer is to allow the caller to pass a callback function and call this for every token, as I have described here: Split a String in C.There are some problems with strtok() listed here: http://benpfaff.org/writings/clc/strtok.html
Hence, it is better to avoid strtok.
Now, consider a string containing a empty field as follows:
You can use simple function to be able convert String in CSV format to read them to a float Array:
We specified the delimiter here as a comma. It works with other single character delimiter.
Please find the Usage below:
Output is as follows :
Here is my two cents:
Usage: