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,
If you are willing to use an external library, I can't recommend bstrlib enough. It takes a little extra setup, but is easier to use in the long run.
For example, split the string below, one first creates a bstring
with the bfromcstr()
call. (A bstring
is a wrapper around a char buffer).
Next, split the string on commas, saving the result in a struct bstrList
, which has fields qty
and an array entry
, which is an array of bstring
s.
bstrlib
has many other functions to operate on bstring
s
Easy as pie...
#include "bstrlib.h"
#include
int main() {
int i;
char *tmp = "Hello,World,sak";
bstring bstr = bfromcstr(tmp);
struct bstrList *blist = bsplit(bstr, ',');
printf("num %d\n", blist->qty);
for(i=0;iqty;i++) {
printf("%d: %s\n", i, bstr2cstr(blist->entry[i], '_'));
}
}