diff --git a/examples/string_example.c b/examples/string_example.c new file mode 100644 index 0000000..34983ac --- /dev/null +++ b/examples/string_example.c @@ -0,0 +1,10 @@ +#include +#include "../string.h" + + +int main() +{ + char *substr = "Hello, World!"; + struct string_t *str = string_new_slice(substr, 0, 4); + printf("%s\n", str->data); +} diff --git a/string.c b/string.c index 92b3a26..05acec4 100644 --- a/string.c +++ b/string.c @@ -40,6 +40,24 @@ void string_free(struct string_t *s) free(s); } +struct string_t *string_new_slice(const char *data, size_t start, size_t end) +{ + /* why +2? + * 1. Null termination. + * 2. We the entire data from the start position to the end position to be present. + * say start = 0 and end = 1, we want both the 0th char and the 1st char, i.e end - start + 1. + */ + size_t len = end - start + 2; + struct string_t *s = malloc(sizeof(struct string_t)); + s->capacity = __STRING_DEFAULT_CAPACITY__ >= len ? __STRING_DEFAULT_CAPACITY__ : len; + s->data = (char *)(malloc(__CHAR_BIT__ * s->capacity)); + s->length = len; + + memcpy(s->data, data + start, len); + s->data[s->length - 1] = 0; + return s; +} + size_t string_length(const struct string_t *s) { if (s == NULL) diff --git a/string.h b/string.h index a296f94..6a38919 100644 --- a/string.h +++ b/string.h @@ -36,6 +36,8 @@ struct string_t *string_new(const char *data); */ void string_free(struct string_t *str); +struct string_t *string_new_slice(const char *data, size_t start, size_t end); + /** * Gets the length of a string. * @param str The string. @@ -77,4 +79,4 @@ int string_compare(const struct string_t *src, const struct string_t *dest); bool string_equal(const struct string_t *str1, const struct string_t *str2); -#endif \ No newline at end of file +#endif