An stb-style library that provides efficient and convenient dynamic string construction.
This string builder was built with effeciency in mind and it tries not to depend on the standard library too much. Under the hood it uses a simple dynamic array (also called a list or vector) to store the string. All the functions avoid dynamic memory allocations for anything other than increasing storage for the actual string.
- Appending a string
- Appending a formatted string as in
printf
- Replacing a substring with another string
- Inserting a string at the given index
- Other small functions, like appending a value in it's bit representation
#include <stdio.h>
#define STRING_BUILDER_IMPLEMENTATION
#include "string_builder.h"
#define FIELD_SIZE 10
int main() {
StringBuilder b = string_builder_new();
StringBuilder *builder = &b; // Unfortunately, this boilerplate is needed.
string_builder_append_format(builder, "Building a %dx%d field:\n", FIELD_SIZE, FIELD_SIZE);
for (int y = 0; y < FIELD_SIZE; y++) {
string_builder_append_char(builder, '|');
for (int x = 0; x < FIELD_SIZE; x++) {
string_builder_append(builder, ".#..");
}
string_builder_append_char(builder, '|');
string_builder_append_char(builder, '\n');
}
string_builder_replace(builder, "..", ".");
string_builder_replace(builder, ".", " ");
string_builder_insert(builder, 0, "Hello, String Builder!\n");
printf("%s", builder->string);
string_builder_free(builder);
}
// OUTPUT:
// Hello, String Builder!
// Building a 10x10 field:
// | # # # # # # # # # # |
// | # # # # # # # # # # |
// | # # # # # # # # # # |
// | # # # # # # # # # # |
// | # # # # # # # # # # |
// | # # # # # # # # # # |
// | # # # # # # # # # # |
// | # # # # # # # # # # |
// | # # # # # # # # # # |
// | # # # # # # # # # # |
This library and it's functionality were inspired by C#'s String Builder.
Some other string builders in C: