Design Pattern Examples
Overview of object-oriented design patterns
split.c
Go to the documentation of this file.
1
5
6#include <stdlib.h>
7#include <string.h>
8
9#include "split.h"
10
16{
17 if (list != NULL)
18 {
19 list->strings = NULL;
20 list->strings_count = 0;
21 }
22}
23
31{
32 if (list != NULL)
33 {
34 free(list->strings);
35 list->strings = NULL;
36 list->strings_count = 0;
37 }
38}
39
46void SplitList_AddString(SplitList* list, const char* s)
47{
48 if (list != NULL && s != NULL)
49 {
50 const char** new_list = NULL;
51 if (list->strings == NULL)
52 {
53 new_list = calloc(1, sizeof(char*));
54 }
55 else
56 {
57 size_t newSize = (list->strings_count + 1) * sizeof(const char*);
58 new_list = realloc(list->strings, newSize);
59 }
60 if (new_list != NULL)
61 {
62 list->strings = new_list;
63 list->strings[list->strings_count] = s;
64 list->strings_count++;
65 }
66 }
67}
68
70// split()
72void split(char* s, const char* splitChars, SplitList* components)
73{
74 if (s != NULL && components != NULL)
75 {
76 SplitList_Clear(components);
77 if (splitChars == NULL || *splitChars == '\0')
78 {
79 splitChars = " ";
80 }
81 char* work = s;
82 for (;;)
83 {
84 size_t foundIndex = strcspn(work, splitChars);
85 if (foundIndex < strlen(work))
86 {
87 work[foundIndex] = '\0';
88 SplitList_AddString(components, work);
89 work += foundIndex + 1;
90 }
91 else
92 {
93 SplitList_AddString(components, work);
94 break;
95 }
96 }
97 }
98}
Declaration of the split functions, for splitting a string on delimiters.
void SplitList_Clear(SplitList *list)
Clear the given SplitList object so it can be reused again. Releases the list of sub-strings (but doe...
Definition: split.c:30
void SplitList_Initialize(SplitList *list)
Initialize the given SplitList object.
Definition: split.c:15
void split(char *s, const char *splitChars, SplitList *components)
Split the given path into multiple strings based on the given delimiter. The pointers to each string ...
Definition: split.c:72
void SplitList_AddString(SplitList *list, const char *s)
Add a string to the given SplitList object. The string is not duplicated but instead is just copied i...
Definition: split.c:46
Represents a collection of sub-strings split from a single string using the split() function.
Definition: helpers/split.h:17
size_t strings_count
Number of sub-strings.
Definition: helpers/split.h:19
const char ** strings
Pointers to each sub-string.
Definition: helpers/split.h:18