Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions examples/string_example.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#include <stdio.h>
#include "../string.h"


int main()
{
char *substr = "Hello, World!";
struct string_t *str = string_new_slice(substr, 0, 4);
printf("%s\n", str->data);
}
18 changes: 18 additions & 0 deletions string.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 3 additions & 1 deletion string.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
#endif