Project: String Builder

One thing that you may find useful from time to time is the ability to build a string out of pieces. While this can be done to some extent with the sprintf function, even that has its limits. The objective of this project is to make a structure (similar to data_array_list example) that helps you build strings. You need to create a structure called string_builder and the functions given below. All functions should use errno for error handling except for string_buffer_destroy which is not allowed to fail.

You should also write a main function and some code to test your string builder to make sure it works correctly.

String Builder Interface

struct string_builder;

/* Creates a new string builder */
int string_builder_create(struct string_builder *sb);

/* Destroys a new string builder */
void string_builder_destroy(struct string_builder *sb);

/* Shrinks the string_builder to the given length. If the given length
 * is greater than the current length, -1 is returned and errno is set
 * to EINVAL.
 */
int string_builder_shrink(struct string_builder *sb, size_t length);

/* Appends the string "str" to the end of the string builder string */
int string_builder_append(struct string_builder *sb, char *str);

/* Appends a single character to the end of the string builder string */
int string_builder_append_char(struct string_builder *sb, char c);

/* Appends the first n characters of "str" to the string builder string */
int string_builder_append_n(struct string_builder *sb, char *str, size_t n);

/* Inserts the given string into the string builder at the given
 * position.  If the position is after the end, the function returns -1
 * and errno is set to EINVAL.  If the position is in the middle
 * of the string, all of the characters at or after pos get shifted to
 * the right to make room for the new string.
 */
int string_builder_insert(struct string_builder *sb, size_t pos, char *str);

/* Inserts the first n characters of the given string into the string
 * builder at the given position.
 *
 * See also: string_builder_insert.
 */
int string_builder_insert_n(struct string_builder *sb, size_t pos,
        char *str, size_t n);

/* Inserts a single character into the string builder at the given
 * position.
 *
 * See also: string_builder_insert.
 */
int string_builder_insert_char(struct string_builder *sb, size_t pos,
        char c, size_t n);

/* Retrieves the string from the string builder
 *
 * Note: The returned string is guaranteed to be null-terminated
 */
char * string_builder_get_string(struct string_builder *sb);

While this looks like a lot to implement, it isn’t nearly as bad as it looks. There is one particular function that, once you implement it, 5 of the others can be written in one line in terms of this function.