-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic_string.c
More file actions
65 lines (58 loc) · 1.09 KB
/
dynamic_string.c
File metadata and controls
65 lines (58 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// File: dynamic_string.c
// Include this file *after* including <stdlib.h>
typedef struct
{
char * chars;
int len;
int size;
}
string;
string * str_new()
{
string * str = malloc(sizeof(string));
str->len = 0;
str->size = 16;
str->chars = malloc(str->size);
return str;
}
void str_free(string * str)
{
if (str == NULL) return;
free(str->chars);
free(str);
}
void str_realloc_if_full(string * str)
{
if (str->size < 1)
{
str->size = 1;
str->chars = realloc(str->chars, str->size);
}
while (str->len >= str->size)
{
str->size *= 2;
str->chars = realloc(str->chars, str->size);
}
}
void str_null_terminate(string * str)
{
str_realloc_if_full(str);
str->chars[str->len] = '\0';
}
void str_pop_back(string * str)
{
if (str->len < 1) return;
str->len -= 1;
str->chars[str->len] = '\0';
}
void str_push_back(string * str, char c)
{
str_realloc_if_full(str);
str->chars[str->len] = c;
str->len += 1;
}
void str_append(string * str, char * arr)
{
for (char * itr = arr; *itr != '\0'; itr++) str_push_back(str, *itr);
str_null_terminate(str);
}