-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_builder.c
86 lines (77 loc) · 1.55 KB
/
string_builder.c
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "include/string_builder.h"
#include <stdlib.h>
#include <stdio.h>
STRING_BUILDER *init_sb()
{
STRING_BUILDER *sb = malloc(sizeof(STRING_BUILDER));
sb->size = 0;
sb->characters = NULL;
return sb;
}
void free_sb(STRING_BUILDER *sb)
{
if (sb->characters != NULL) {
free(sb->characters);
sb->characters = NULL;
}
free(sb);
sb = NULL;
}
char sb_pop(STRING_BUILDER *sb)
{
char c = sb->characters[sb->size - 1];
char *new_characters =
realloc(sb->characters, (sb->size - 1) * sizeof(char));
if (new_characters) {
sb->characters = new_characters;
} else {
printf("%s\n",
"Could not de-allocate space when popping an element");
}
sb->size--;
return c;
}
char sb_get(STRING_BUILDER *sb, int index)
{
if (index > sb->size - 1 || index < 0) {
return 0;
}
char c = sb->characters[index];
return c;
}
void sb_append_char(STRING_BUILDER *sb, char c)
{
if (!sb->characters) {
sb->characters = malloc(sizeof(char));
} else {
char *newchars =
realloc(sb->characters, (sb->size + 1) * sizeof(char));
if (newchars) {
sb->characters = newchars;
} else {
printf("%s\n",
"Could not allocate space for next character");
}
}
sb->characters[sb->size] = c;
sb->size++;
}
void sb_append_int(STRING_BUILDER *sb, int number)
{
char buf[20];
sprintf(buf, "%d", number);
sb_append(sb, buf);
}
// TODO: optimize this
void sb_append(STRING_BUILDER *sb, char *c)
{
while (*c != '\0') {
sb_append_char(sb, *c);
c += 1;
}
}
char *sb_build(STRING_BUILDER *sb)
{
sb_append_char(sb, '\0');
return sb->characters;
}