I'm trying to implement a function that takes a string to parse and delimiter string as inputs, then returns a char array containing these parsed elements including empty chars if two delimiters are adjacent.
Below is my current code:
String* _split(String self, String delim) {
char* selfCharArr = _get_value(self, NULL);
char* delimCharArr = _get_value(delim, NULL);
char** tokens = calloc((_length(self) + 2), sizeof(String));
char* var;
int index = 0;
var = strsep(&selfCharArr, delimCharArr);
while(var != NULL) {
var = strsep(&selfCharArr, delimCharArr);
tokens[index] = var;
index++;
}
return (String*) tokens;
}
However, in testing I am finding that this will only return a NULL string, and I can't figure out why. No warnings or errors are produced and I've consulted the man pages.
assert(index < _length(self) + 2);
beforetokens[index]
as a first measure. Also, why is that you havechar **tokens
yet you allocatecalloc(..., sizeof(String))
? I think it would be better to justrealloc
thetokens
pointer in the loop.