C Collections

cstring · Section 3

cstring_split

cstring_split - split the string by a delimiter

C Collections (libccollections, -lccollections)

#include <ccollections/cstring.h>
 
cvec cstring_split(cstr s, const char *delimiter, char **err);

This function splits s at every non-overlapping occurrence of delimiter
and returns the tokens as a cvec of cstr (elem_size == sizeof(cstr)). An
empty token is kept when the string begins or ends with the delimiter and
when two delimiters follow each other. If delimiter is not found, the
vector holds one token equal to the original string.

s            String to split
delimiter    Separator string (must not be NULL or empty)
err          Optional pointer to receive an error string on failure

A cvec that holds the tokens, each one a cstr with its own heap allocation
NULL on failure, with the details written to *err when err is not NULL

The caller has to destroy every cstr inside the vector and then the
vector itself:
  cvec parts = cstring_split(s, ",", NULL);
  if (parts) {
    for (size_t i = 0; i < cvector_size(parts); i++) {
      cstr *p = (cstr *)cvector_at(parts, i);
      cstring_destroy(*p);
    }
    cvector_destroy(parts);
  }
Asserts if s is NULL.

cstring_find(3), cstring_substring(3)