Skip to content
Gustav Louw edited this page Jan 13, 2021 · 7 revisions
#include <str.h>

The CTL str, analogous to the STL std::string, is a extension of vec of type T char. The implementation extends that of vec, and such inherits the functions defined in vec, with the key difference being that all instantiations of vec_char are replaced with str. The implementation in str.h is defined as:

#define vec_char str
#define P
#define T char
#include <vec.h>

Strings ease the end user complexity of C-style strings (char*). All string functions utilize a C-style string as their second argument for general ease of use.

The str type is null terminated under all circumstances, but, like a conventional vec, member size can be referenced to determine the number of characters within a string, excluding the null termination byte.

Example: Appending Strings

The second argument of string functions are of type char*, adding an element of flexibility to various string operations: str types can append, or perform any other operation, by using standard "quoted" strings, by referencing their value member directly, or by using either str_c_str() or str_data() functions to access said value member.

#include <stdio.h>
#include <str.h>

int main(void)
{
    str a = str_init("The");
    str b = str_init("C");
    str c = str_init("Library");
    str_append(&a, " ");
    str_append(&a, b.value); // Uses `char* value` directly.
    str_append(&a, " ");
    str_append(&a, "Template"); // Uses a C-style string directly.
    str_append(&a, " ");
    str_append(&a, str_c_str(&c)); // str_c_str returns `c.value`, same as str_data().
    puts(a.value);
    puts(str_c_str(&a));
    puts(str_data(&a));
    printf("1: using printf: %s\n", a.value);
    printf("2: using printf: %s\n", str_c_str(&a));
    printf("3: using printf: %s\n", str_data(&a));
    str_free(&a);
    str_free(&b);
    str_free(&c);
}

Like C++11, the value member is returned by both str_c_str() and str_data(), and is always terminated with a null byte, regardless of the function called.

Clone this wiki locally