C Collections

cstring · Section 3

cstr_substring

cstr_substring - create a new string from a sub-range, and call ccol__fatal_err() on failure

C Collections (libccollections, -lccollections)

#include <ccollections/cstring.h>
 
cstr result = cstr_substring(s, start, len);

This macro is a GNU C statement expression that calls cstring_substring()
and calls ccol__fatal_err() when the result is NULL, which happens only
when an allocation failed. The new cstring is the value of the macro, so
you can use it directly inside an expression.

s      Source cstr
start  Zero-based start index
len    Number of characters to include

A new cstr that holds the sub-range that you asked for

The macro uses a GNU C statement expression ({...}), so it needs GCC or
Clang.
A range that runs past the end of the string is clamped at the end
instead of being rejected.
You must destroy the cstring that this macro returns.
The macro evaluates each of s, start and len exactly once, so the failure
message reports the start and the length that the call really used.
If you want to handle an error yourself, call cstring_substring()
directly.

cstr_construct(src, "Hello, world!");
cstr sub = cstr_substring(src, 7, 5);   /* "world" */
printf("%s\n", cstr_c_str(sub));
cstr_destroy(sub);
cstr_destroy(src);

cstring_substring(3), cstr_copy(3), cstr_split(3)