Skip to main content
Removed tags from title
Link
Do not put tags in title
Link
Rob
  • 15.1k
  • 30
  • 48
  • 72

C: How to correctly use strsep() to parse an array?

Source Link

C: How to correctly use strsep() to parse an array?

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.