Design Pattern Examples
Overview of object-oriented design patterns
dynamicstring.c
Go to the documentation of this file.
1
5
6#include <stdlib.h>
7#include <string.h>
8
9#include "dynamicstring.h"
10
11
13// DynamicString_Initialize()
16{
17 if (string != NULL)
18 {
19 string->string = calloc(1, 1); // An empty string
20 string->length = 0;
21 }
22}
23
25// DynamicString_Clear()
28{
29 if (string != NULL)
30 {
31 free(string->string);
33 }
34}
35
37// DynamicString_Append()
39bool DynamicString_Append(DynamicString* string, const char* s)
40{
41 bool success = false;
42
43 if (string != NULL && s != NULL)
44 {
45 char* newText = NULL;
46 size_t newSize = string->length + strlen(s) + 1;
47 if (string->string == NULL)
48 {
49 newText = calloc(1, newSize);
50 }
51 else
52 {
53 newText = realloc(string->string, newSize);
54 }
55 if (newText != NULL)
56 {
57 newText[string->length] = '\0';
58 string->string = newText;
59 // Previous code ensures there is space for s and string is zero-
60 // terminated.
61 strcat(string->string, s);
62 string->length = strlen(string->string);
63 success = true;
64 }
65 }
66
67 return success;
68}
69
71// DynamicString_Set()
73bool DynamicString_Set(DynamicString* string, const char* s)
74{
75 bool success = false;
76
77 if (string != NULL)
78 {
79 DynamicString_Clear(string);
80 success = DynamicString_Append(string, s);
81 }
82
83 return success;
84}
void DynamicString_Clear(DynamicString *string)
Clear a DynamicString object, releasing any allocated memory. Resets to an empty string.
Definition: dynamicstring.c:27
void DynamicString_Initialize(DynamicString *string)
Initialize a DynamicString object to an empty string.
Definition: dynamicstring.c:15
bool DynamicString_Set(DynamicString *string, const char *s)
Set the DynamicString object to the specified string, replacing whatever is in the DynamicString obje...
Definition: dynamicstring.c:73
bool DynamicString_Append(DynamicString *string, const char *s)
Append the specified string to the DynamicString object.
Definition: dynamicstring.c:39
Declaration of the DynamicString structure and supporting functions to work with dynamic strings.
Represents a string that can be grown dynamically.
Definition: dynamicstring.h:16
char * string
The string that can grow.
Definition: dynamicstring.h:17