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,',');
Below is my
strtok()
implementation from zString library.zstring_strtok()
differs from standard library'sstrtok()
in the way it treats consecutive delimiters.Just have a look at the code below,sure that you will get an idea about how it works (I tried to use as many comments as I could)
Below is an example usage...
The library can be downloaded from Github https://github.com/fnoyanisi/zString
For: Hassan A. El-Seoudy
Your ticket is closed so I can't respond to it ^^'. But you can try this:
Method below will do all the job (memory allocation, counting the length) for you. More information and description can be found here - Implementation of Java String.split() method to split C string
How to use it:
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 thebfromcstr()
call. (Abstring
is a wrapper around a char buffer). Next, split the string on commas, saving the result in astruct bstrList
, which has fieldsqty
and an arrayentry
, which is an array ofbstring
s.bstrlib
has many other functions to operate onbstring
sEasy as pie...
In the above example, there would be a way to return an array of null terminated strings (like you want) in place in the string. It would not make it possible to pass a literal string though, as it would have to be modified by the function:
There is probably a neater way to do it, but you get the idea.
Explode & implode - initial string remains intact, dynamic memory allocation
Usage: