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,',');
My version:
This is different approach, working for large files too. https://onlinegdb.com/BJlWVdzGf
My code (tested):
Result:
This may solve your purpose
Output :
Not tested, probably wrong, but should give you a good head-start at how it should work:
I think
strsep
is still the best tool for this:That is literally one line that splits a string.
The extra parentheses are a stylistic element to indicate that we're intentionally testing the result of an assignment, not an equality operator
==
.For that pattern to work,
token
andstr
both have typechar *
. If you started with a string literal, then you'd want to make a copy of it first:If two delimiters appear together in
str
, you'll get atoken
value that's the empty string. The value ofstr
is modified in that each delimiter encountered is overwritten with a zero byte - another good reason to copy the string being parsed first.In a comment, someone suggested that
strtok
is better thanstrsep
becausestrtok
is more portable. Ubuntu and Mac OS X havestrsep
; it's safe to guess that other unixy systems do as well. Windows lacksstrsep
, but it hasstrbrk
which enables this short and sweetstrsep
replacement:Here is a good explanation of
strsep
vsstrtok
. The pros and cons may be judged subjectively; however, I think it's a telling sign thatstrsep
was designed as a replacement forstrtok
.