Need help with str?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

171 Stars 13 Forks BSD 3-Clause "New" or "Revised" License 92 Commits 0 Opened issues


str: yet another string library for C language.

Services available


Need anything else?

Contributors list

No Data

str: yet another string library for C language.

License: BSD 3 Clause


Bored with developing the same functionality over and over again, unsatisfied with existing libraries, so decided to make the right one, once and forever. 🙂


  • Handles both C and binary strings;
  • Light-weight references to strings: cheap to create, copy, or pass by value;
  • Support for copy and move semantics, although not enforceable by the C language;
  • String composition functions writing to memory, file descriptors, or file streams;


Just clone the project and copy (or symlink) the files

into your project, but please respect the license.

Code Examples

String composition:

str s = str_null;

str_join(&s, str_lit(", "), str_lit("Here"), str_lit("there"), str_lit("and everywhere"));

str_cat(&s, s, str_lit("..."));

assert(str_eq(s, str_lit("Here, there, and everywhere..."))); str_free(s);

Same as above, but writing to a file:

FILE* const stream = fopen(...);

int err = str_join(stream, str_lit(", "), str_lit("Here"), str_lit("there"), str_lit("and everywhere..."));

if(err != 0) { /* handle the error */ }

Discussion on Hacker News.

User Guide

Disclaimer: This is the good old C language, not C++ or Rust, so nothing can be enforced on the language level, and certain discipline is required to make sure there is no corrupt or leaked memory resulting from using this library.

A string is represented by the type

that maintains a pointer to some memory containing the actual string. Objects of type
are small enough (a struct of a
const char*
and a
) to be cheap to create, copy (pass by value), and move. The
structure should be treated as opaque (i.e., do not attempt to directly access or modify the fields in this structure). The strings are assumed to be immutable, like those in Java or Go, but only by means of
const char*
pointers, so it is actually possible to write to such a string, although the required type cast to
offers at least some (mostly psychological) protection from modifying a string by mistake.

This library focusses only on handling strings, not gradually composing them like StringBuffer class in Java.

All string objects must be initialised. Uninitialised objects will cause undefined behaviour. Use the provided constructors, or

for empty strings.

There are two kinds of

objects: those actually owning the memory they point to, and non-owning references. This property can be queried using
functions, otherwise such objects are indistinguishable.

Non-owning string objects are safe to copy and assign to each other, as long as the memory they refer to is valid. They do not need to be freed.

is a no-op for reference objects. A reference object can be cheaply created from a C string, a string literal, or from a range of bytes.

Owning objects require special treatment, in particular: * It is a good idea to have only one owning object per each allocated string, but such a string can have many references to its underlying string, as long as those references do not outlive the owning object. Sometimes this rule may be relaxed for code clarity, like in the above example where the owning object is passed directly to a function, but only if the function does not store or release the object. When in doubt pass such an object via

. * Direct assignments (like
s2 = s1;
) to owning objects will certainly leak memory, use
function instead. In fact, this function can assign to any string object, owning or not, so it can be used everywhere, just to avoid any doubt. * There is no automatic memory management in C, so every owning object must be released at some point, either directly by using
function, or indirectly by assignment from
or a similar function. * An owning object can be passed over to another location by using
function. The function resets its source object to an empty string.

It is technically possible to create a reference to a string that is not null-terminated. The library accepts strings without null-terminators, but every new string allocated by the library is guaranteed to be null-terminated.

String Construction

A string object can be constructed form any C string, string literal, or a range of bytes. The provided constructors are computationally cheap to apply. Depending on the constructor, the new object can either own the actual string it refers to, or be a non-owning reference. Constructors themselves do not allocate any memory. Importantly, constructors are the only functions in this library that return a string object, while others assign their results through a pointer to a pre-existing string. This makes constructors suitable for initialisation of new string objects. In all other situations one should combine construction with assignment, for example:

str_assign(&dest, str_acquire_chars(buff, n));

String Object Properties

Querying a property of a string object (like the length of the string via

) is a cheap operation.

Assigning and Moving String Objects

C language does not allow for operator overloading, so this library provides a function

that takes a string object and assigns it to the destination object, freeing any memory owned by the destination. It is generally recommended to use this function everywhere outside object initialisation.

An existing object can be moved over to another location via

function. The function resets the source object to
to guarantee the correct move semantics. The value returned by
may be either used to initialise a new object, or assigned to an existing object using

String Composition and Generic Destination

String composition functions can write their results to different destinations, depending on the type of their

  • str*
    : result is assigned to the string object;
  • int
    : result is written to the file descriptor;
  • FILE*
    result is written to the file stream.

The composition functions return 0 on success, or the value of

as retrieved at the point of failure (including
on memory allocation error).

Detailed Example

Just to make things more clear, here is the same code as in the example above, but with comments: ```C // declare a variable and initialise it with an empty string str s = str_null;

// join the given string literals around the separator (second parameter), // storing the result in object "s" (first parameter); in this example we do not check // the return values of the composition functions, thus ignoring memory allocation failures, // which is probably not the best idea in general. strjoin(&s, strlit(", "), strlit("Here"), strlit("there"), str_lit("and everywhere"));

// create a new string concatenating "s" and a literal; the function does not modify its // destination object "s" before the result is computed, also freeing the destination // before the assignment, so it is safe to use "s" as both a parameter and a destination. // note: we pass a copy of the owning object "s" as the second parameter, and here it is // safe to do so because this particular function does not store or release its arguments. strcat(&s, s, strlit("..."));

// check that we have got the expected result assert(streq(s, strlit("Here, there, and everywhere...")));

// finally, free the memory allocated for the string str_free(s); ```

There are some useful code snippets provided to assist with writing code using this library.

API brief

typedef struct { ... } str;

The string object.

String Properties

size_t str_len(const str s)

Returns the number of bytes in the string referenced by the object.

const char* str_ptr(const str s)

Returns a pointer to the first byte of the string referenced by the object. The pointer is never NULL.

const char* str_end(const str s)

Returns a pointer to the next byte past the end of the string referenced by the object. The pointer is never NULL, but it is not guaranteed to point to any valid byte or location. For C strings it points to the terminating null character. For any given string
the following condition is always satisfied:
str_end(s) == str_ptr(s) + str_len(s)

bool str_is_empty(const str s)

Returns "true" for empty strings.

bool str_is_owner(const str s)

Returns "true" if the string object is the owner of the memory it references.

bool str_is_ref(const str s)

Returns "true" if the string object does not own the memory it references.

String Construction


Empty string constant.

str str_lit(s)

Constructs a non-owning object from a string literal. Implemented as a macro.

str str_ref(s)

Constructs a non-owning object from either a null-terminated C string, or another
object. Implemented as a macro.

str str_ref_chars(const char* const s, const size_t n)

Constructs a non-owning object referencing the given range of bytes.

str str_acquire_chars(const char* const s, const size_t n)

Constructs an owning object for the specified range of bytes. The pointer
should be safe to pass to

str str_acquire(const char* const s)

Constructs an owning object from the given C string. The string should be safe to pass to

str str_move(str* const ps)

Saves the given object to a temporary, resets the source object to
, and then returns the saved object.

String Modification

void str_assign(str* const ps, const str s)

Assigns the object
to the object pointed to by
. Any memory owned by the target object is freed before the assignment.

void str_clear(str* const ps)

Sets the target object to
after freeing any memory owned by the target.

void str_swap(str* const s1, str* const s2)

Swaps two string objects.

int str_from_file(str* const dest, const char* const file_name)

Reads the entire file (of up to 64MB by default, configurable via
) into the destination string. Returns 0 on success, or the value of
on error.

String Comparison

int str_cmp(const str s1, const str s2)

Lexicographically compares the two string objects, with usual semantics.

bool str_eq(const str s1, const str s2)

Returns "true" if the two strings match exactly.

int str_cmp_ci(const str s1, const str s2)

Case-insensitive comparison of two strings, implemented using

bool str_eq_ci(const str s1, const str s2

Returns "true" is the two strings match case-insensitively.

bool str_has_prefix(const str s, const str prefix)

Tests if the given string
starts with the specified prefix.

bool str_has_suffix(const str s, const str suffix)

Tests if the given string
ends with the specified suffix.

String Composition

int str_cpy(dest, const str src)

Copies the source string referenced by
to the generic destination
. Returns 0 on success, or the value of
on failure.

int str_cat_range(dest, const str* src, size_t count)

strings from the array starting at address
, and writes the result to the generic destination
. Returns 0 on success, or the value of
on failure.

int str_cat(dest, ...)

Concatenates a variable list of
arguments, and writes the result to the generic destination
. Returns 0 on success, or the value of
on failure.

int str_join_range(dest, const str sep, const str* src, size_t count)

Joins around
strings from the array starting at address
, and writes the result to the generic destination
. Returns 0 on success, or the value of
on failure.

int str_join(dest, const str sep, ...)

Joins a variable list of
arguments around
delimiter, and writes the result to the generic destination
. Returns 0 on success, or the value of
on failure.

Searching and Sorting

bool str_partition(const str src, const str patt, str* const prefix, str* const suffix)

Splits the string
on the first match of
, assigning a reference to the part of the string before the match to the
object, and the part after the match to the
object. Returns
if a match has been found, or
otherwise, also setting
to reference the entire
string, and clearing the
object. Empty pattern
never matches.

void str_sort_range(const str_cmp_func cmp, str* const array, const size_t count)

Sorts the given array of
objects using the given comparison function. A number of typically used comparison functions is also provided: *
(ascending sort) *
(descending sort) *
(ascending case-insensitive sort) *
(descending case-insensitive sort)

const str* str_search_range(const str key, const str* const array, const size_t count)

Binary search for the given key. The input array must be sorted using
. Returns a pointer to the string matching the key, or NULL.

size_t str_partition_range(bool (*pred)(const str), str* const array, const size_t count)

Reorders the string objects in the given range in such a way that all elements for which the predicate
returns "true" precede the elements for which predicate
returns "false". Returns the number of preceding objects.

size_t str_unique_range(str* const array, const size_t count)

Reorders the string objects in the given range in such a way that there are two partitions: one where each object is unique within the input range, and another partition with all the remaining objects. The unique partition is stored at the beginning of the array, and is sorted in ascending order, followed by the partition with all remaining objects. Returns the number of unique objects.

UNICODE support

for_each_codepoint(var_name, src_string)

A macro that expands to a loop iterating over the given string
(of type
) by UTF-32 code points. On each iteration the variable
(of type
) is assigned the value of the next valid UTF-32 code point from the source string. Upon exit from the loop the variable has one on the following values: *
: the iteration has reached the end of source string; *
: an incomplete byte sequence has been detected; *
: an invalid byte sequence has been detected.

The source string is expected to be encoded in the current program locale, as set by the most recent call to


Usage pattern: ```c


... str s = ... ... char32_t c; // variable to receive UTF-32 values on each iteration

foreachcodepoint(c, s) { /* process c */ }

if(c != CPIENDOF_STRING) { /* handle error */ } ```


Tokeniser interface provides functionality similar to

function. The tokeniser is fully re-entrant with no hidden state, and its input string is not modified while being parsed.
Typical usage:
// declare and initialise tokeniser state
str_tok_state state;

str_tok_init(&state, source_string, delimiter_set);

// object to receive tokens str token = str_null;

// token iterator while(str_tok(&token, &state)) { /* process "token" */ }

Tokeniser API

void str_tok_init(str_tok_state* const state, const str src, const str delim_set)

Initialises tokeniser state with the given source string and delimiter set. The delimiter set is treated as bytes, not as UNICODE code points encoded in UTF-8.

bool str_tok(str* const dest, str_tok_state* const state)

Retrieves the next token and stores it in the
object. Returns
if the token has been read, or
if the end of input has been reached. Retrieved token is always a reference to a slice of the source string.

void str_tok_delim(str_tok_state* const state, const str delim_set)

Changes the delimiter set associated with the given tokeniser state. The delimiter set is treated as bytes, not as UNICODE code points encoded in UTF-8.


All the tools are located in

directory. Currently, there are the following tools:
  • file-to-str
    : The script takes a file (text or binary) and a C variable name, and writes to
    C source code where the variable (of type
    ) is defined and initialised with the content of the file.
  • gen-char-class
    : Generates character classification functions that do the same as their
    counterparts under the current locale as specified by
    environment variable. Run
    tools/gen-char-class --help
    for further details, or
    tools/gen-char-class --space
    to see an example of its output.

Project Status

The library requires at least a C11 compiler. So far has been tested on Linux Mint 19.3 and 20, with

versions up to 9.3.0, and
versions up to 11.0.0; it is also reported to work on ALT Linux 9.1 for Elbrus, with
version 1.25.09.

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.