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 is a string splitting function that can handle multi-character delimiters. Note that if the delimiter is longer than the string that is being split, then
buffer
andstringLengths
will be set to(void *) 0
, andnumStrings
will be set to0
.This algorithm has been tested, and works. (Disclaimer: It has not been tested for non-ASCII strings, and it assumes that the caller gave valid parameters)
Sample code:
Libraries:
Try use this.
You can use the
strtok()
function to split a string (and specify the delimiter to use). Note thatstrtok()
will modify the string passed into it. If the original string is required elsewhere make a copy of it and pass the copy tostrtok()
.EDIT:
Example (note it does not handle consecutive delimiters, "JAN,,,FEB,MAR" for example):
Output:
String tokenizer this code should put you in the right direction.
This function takes a char* string and splits it by the deliminator. There can be multiple deliminators in a row. Note that the function modifies the orignal string. You must make a copy of the original string first if you need the original to stay unaltered. This function doesn't use any cstring function calls so it might be a little faster than others. If you don't care about memory allocation, you can allocate sub_strings at the top of the function with size strlen(src_str)/2 and (like the c++ "version" mentioned) skip the bottom half of the function. If you do this, the function is reduced to O(N), but the memory optimized way shown below is O(2N).
The function:
How to use it: