1 # String
2
3 UCX strings store character arrays together with a length and come in two variants: immutable (`cxstring`) and mutable (`cxmutstr`).
4
5 In general, UCX strings are *not* necessarily zero-terminated.
6 If a function guarantees to return a zero-terminated string, it is explicitly mentioned in the documentation.
7 As a rule of thumb, you _should not_ pass a character array of a UCX string structure to another API without explicitly
8 ensuring that the string is zero-terminated.
9
10 ## Basics
11
12 The following listing shows basic string functions.
13
14 > To simplify documentation, we introduce the pseudo-type `AnyStr` with the meaning that
15 > any UCX string and any C string are supported.
16 > The implementation is actually hidden behind a macro which uses `cx_strcast()` to guarantee compatibility.
17 {style="note"}
18
19 ```C
20 #include <cx/string.h>
21
22 struct cx_string_s {const char *ptr; size_t length;};
23
24 struct cx_mutstr_s {char *ptr; size_t length;};
25
26 typedef struct cx_string_s cxstring;
27
28 typedef struct cx_mutstr_s cxmutstr;
29
30 cxstring cx_str(const char *cstring);
31
32 cxstring cx_strn(const char *cstring, size_t length);
33
34 cxmutstr cx_mutstr(char *cstring);
35
36 cxmutstr cx_mutstrn(char *cstring, size_t length);
37
38 cxmutstr cx_strdup(AnyStr string);
39
40 cxmutstr cx_strdup_a(const CxAllocator *allocator, AnyStr string);
41
42 int cx_strcpy(cxmutstr *dest, cxstring source);
43
44 int cx_strcpy_a(const CxAllocator *allocator,
45 cxmutstr *dest, cxstring source);
46
47 void cx_strfree(cxmutstr *str);
48
49 void cx_strfree_a(const CxAllocator *alloc, cxmutstr *str);
50
51
52 #define CX_SFMT(s) (int) (s).length, (s).ptr
53 #define CX_PRIstr ".*s"
54 #define cx_strcast(s) // converts any string to cxstring
55 ```
56
57 The functions `cx_str()` and `cx_mutstr()` create a UCX string from a `const char*` or a `char*`
58 and compute the length with a call to stdlib `strlen()` (except for `NULL` in which case the length is set to zero).
59 In case you already know the length, or the string is not zero-terminated, you can use `cx_strn()` or `cx_mutstrn()`.
60
61 The function `cx_strdup_a()` allocates new memory with the given `allocator` and copies the given `string`
62 and guarantees that the result string is zero-terminated.
63 The function `cx_strdup()` is equivalent to `cx_strdup_a()`, except that it uses the [default allocator](allocator.h.md#default-allocator).
64
65 The functions `cx_strcpy_a()` and `cx_strcpy()` copy the contents of the `source` string to the `dest` string,
66 and also guarantee zero-termination of the resulting string.
67 The memory in `dest` is either freshly allocated or re-allocated to fit the size of the string plus the terminator.
68
69 Allocated strings are always of type `cxmutstr` and can be deallocated by a call to `cx_strfree()` or `cx_strfree_a()`.
70 The caller must make sure to use the correct allocator for deallocating a string.
71 It is safe to call these functions multiple times on a given string, as the pointer will be nulled and the length set to zero.
72 It is also safe to call the functions with a `NULL`-pointer, just like any other `free()`-like function.
73
74 When you want to use a UCX string in a `printf`-like function, you can use the macro `CX_PRIstr` for the format specifier,
75 and the `CX_SFMT(s)` macro to expand the arguments.
76
77 > When you want to convert a string _literal_ into a UCX string, you can also use the `cx_str()` function.
78 > With optimizations turned on, this function gets inlined and optimizes the call to `strlen()` out, giving
79 > you a `cxstring` structure at zero cost with the length calculated at compile-time.
80
81 ## Comparison
82
83 ```C
84 #include <cx/string.h>
85
86 int cx_strcmp(AnyStr s1, AnyStr s2);
87
88 int cx_strcmp_p(const void *s1, const void *s2);
89
90 int cx_strcasecmp_p(const void *s1, const void *s2);
91
92 bool cx_strprefix(AnyStr string, AnyStr prefix);
93
94 bool cx_strsuffix(AnyStr string, AnyStr suffix);
95
96 int cx_strcasecmp(AnyStr s1, AnyStr s2);
97
98 bool cx_strcaseprefix(AnyStr string, AnyStr prefix);
99
100 bool cx_strcasesuffix(AnyStr string, AnyStr suffix);
101 ```
102
103 The `cx_strcmp()` function compares two strings lexicographically
104 and returns an integer greater than, equal to, or less than 0, if `s1` is greater than, equal to, or less than `s2`, respectively.
105
106 The `cx_strcmp_p()` function takes pointers to UCX strings (i.e., only to `cxstring` and `cxmutstr`) and the signature is compatible with `cx_compare_func`.
107 Use this as a compare function for lists or other data structures.
108
109 The functions `cx_strprefix()` and `cx_strsuffic()` check if `string` starts with `prefix` or ends with `suffix`, respectively.
110
111 The functions `cx_strcasecmp()`, `cx_strcasecmp_p()`, `cx_strcaseprefix()`, and `cx_strcasesuffix()` are equivalent,
112 except that they compare the strings case-insensitive.
113
114 > In the current version of UCX, case-insensitive comparisons are only guaranteed to work with ASCII characters.
115 {style="note"}
116
117 ## Concatenation
118
119 ```C
120 #include <cx/string.h>
121
122 cxmutstr cx_strcat(size_t count, ... );
123
124 cxmutstr cx_strcat_a(const CxAllocator *alloc, size_t count, ... );
125
126 cxmutstr cx_strcat_m(cxmutstr str, size_t count, ... );
127
128 cxmutstr cx_strcat_ma(const CxAllocator *alloc,
129 cxmutstr str, size_t count, ... );
130
131 size_t cx_strlen(size_t count, ...);
132 ```
133
134 The `cx_strcat_a()` function takes `count` UCX strings,
135 allocates memory for a concatenation of those strings _with a single allocation_,
136 and copies the contents of the strings to the new memory.
137 `cx_strcat()` is equivalent, except that it uses the [default allocator](allocator.h.md#default-allocator).
138
139 The `cx_strcat_ma()` and `cx_strcat_m()` append the `count` strings to the specified string `str` and,
140 instead of allocating new memory, reallocate the existing memory in `str`.
141 If the pointer in `str` is `NULL`, there is no difference to `cx_strcat_a()`.
142 Note, that `count` always denotes the number of variadic arguments in _both_ variants.
143
144 The function `cx_strlen()` sums the length of the specified strings.
145
146 > There is no reason to use `cx_strlen()` for a single UCX string.
147 > You can access the `length` field of the structure directly.
148
149 > You can mix `cxstring` and `cxmutstr` in the variadic arguments without the need of `cx_strcast()`.
150
151 ## Find Characters and Substrings
152
153 ```C
154 #include <cx/string.h>
155
156 cxstring cx_strchr(cxstring string, int chr);
157
158 cxstring cx_strrchr(cxstring string, int chr);
159
160 cxstring cx_strstr(cxstring string, cxstring search);
161
162 cxstring cx_strsubs(cxstring string, size_t start);
163
164 cxstring cx_strsubsl(cxstring string, size_t start, size_t length);
165
166 cxstring cx_strtrim(cxstring string);
167
168 cxmutstr cx_strchr_m(cxmutstr string, int chr);
169
170 cxmutstr cx_strrchr_m(cxmutstr string, int chr);
171
172 cxmutstr cx_strstr_m(cxmutstr string, cxstring search);
173
174 cxmutstr cx_strsubs_m(cxmutstr string, size_t start);
175
176 cxmutstr cx_strsubsl_m(cxmutstr string, size_t start, size_t length);
177
178 cxmutstr cx_strtrim_m(cxmutstr string);
179 ```
180
181 The functions `cx_strchr()`, `cx_strrchr()`, and `cx_strstr()`, behave like their stdlib counterparts.
182
183 The function `cx_strsubs()` returns the substring starting at the specified `start` index,
184 and `cx_strsubsl()` returns a substring with at most `length` bytes.
185
186 The function `cx_strtrim()` returns the substring that results when removing all leading and trailing
187 whitespace characters.
188
189 All functions with the `_m` suffix behave exactly the same as their counterparts without `_m` suffix,
190 except that they operate on a `cxmustr`.
191 In _both_ variants the functions return a view into the given `string`
192 and thus the returned strings must never be passed to `cx_strfree()`.
193
194 ## Replace Substrings
195
196 ```C
197 #include <cx/string.h>
198
199 cxmutstr cx_strreplace(cxstring str,
200 cxstring search, cxstring replacement);
201
202 cxmutstr cx_strreplace_a(const CxAllocator *allocator, cxstring str,
203 cxstring search, cxstring replacement);
204
205 cxmutstr cx_strreplacen(cxstring str,
206 cxstring search, cxstring replacement, size_t replmax);
207
208 cxmutstr cx_strreplacen_a(const CxAllocator *allocator, cxstring str,
209 cxstring search, cxstring replacement, size_t replmax);
210 ```
211
212 The function `cx_strreplace()` allocates a new string which will contain a copy of `str`
213 where every occurrence of `search` is replaced with `replacement`.
214 The new string is guaranteed to be zero-terminated even if `str` is not.
215
216 The function `cx_strreplace_a()` uses the specified `allocator` to allocate the new string.
217
218 The functions `cx_strreplacen()` and `cx_strreplacen_a()` are equivalent, except that they stop
219 after `replmax` number of replacements.
220
221 ## Basic Splitting
222
223 ```C
224 #include <cx/string.h>
225
226 size_t cx_strsplit(cxstring string, cxstring delim,
227 size_t limit, cxstring *output);
228
229 size_t cx_strsplit_a(const CxAllocator *allocator,
230 cxstring string, cxstring delim,
231 size_t limit, cxstring **output);
232
233 size_t cx_strsplit_m(cxmutstr string, cxstring delim,
234 size_t limit, cxmutstr *output);
235
236 size_t cx_strsplit_ma(const CxAllocator *allocator,
237 cxmutstr string, cxstring delim,
238 size_t limit, cxmutstr **output);
239 ```
240
241 The `cx_strsplit()` function splits the input `string` using the specified delimiter `delim`
242 and writes the substrings into the pre-allocated `output` array.
243 The maximum number of resulting strings can be specified with `limit`.
244 That means, at most `limit-1` splits are performed.
245 The function returns the actual number of items written to `output`.
246
247 On the other hand, `cx_strsplit_a()` uses the specified `allocator` to allocate the output array,
248 and writes the pointer to the allocated memory to `output`.
249
250 The functions `cx_strsplit_m()` and `cx_strsplit_ma()` are equivalent to `cx_strsplit()` and `cx_strsplit_a()`,
251 except that they work on `cxmustr` instead of `cxstring`.
252
253 > The `allocator` in `cx_strsplit_a()` and `cx_strsplit_ma()` is _only_ used to allocate the output array.
254 > The strings will always point into the original `string`
255 > and you need to use `cx_strdup()` or `cx_strdup_a()` if you want copies or zero-terminated strings after performing the split.
256 {style="note"}
257
258 ## Complex Tokenization
259
260 ```C
261 #include <cx/string.h>
262
263 CxStrtokCtx cx_strtok(AnyStr str, AnyStr delim, size_t limit);
264
265 void cx_strtok_delim(CxStrtokCtx *ctx,
266 const cxstring *delim, size_t count);
267
268 bool cx_strtok_next(CxStrtokCtx *ctx, cxstring *token);
269
270 bool cx_strtok_next_m(CxStrtokCtx *ctx, cxmutstr *token);
271 ```
272
273 You can tokenize a string by creating a _tokenization_ context with `cx_strtok()`,
274 and calling `cx_strtok_next()` or `cx_strtok_next_m()` as long as they return `true`.
275
276 The tokenization context is initialized with the string `str` to tokenize,
277 one delimiter `delim`, and a `limit` for the maximum number of tokens.
278 When `limit` is reached, the remaining part of `str` is returned as one single token.
279
280 You can add additional delimiters to the context by calling `cx_strtok_delim()`, and
281 specifying an array of delimiters to use.
282
283 > Regardless of how the context was initialized, you can use either `cx_strtok_next()`
284 > or `cx_strtok_next_m()` to retrieve the tokens. However, keep in mind that modifying
285 > characters in a token returned by `cx_strtok_next_m()` has only defined behavior, when the
286 > underlying `str` is a `cxmutstr`.
287
288 ### Example
289
290 ```C
291 #include <cx/string.h>
292
293 cxstring str = cx_str("an,arbitrarily;||separated;string");
294
295 // create the context
296 CxStrtokCtx ctx = cx_strtok(str, ",", 10);
297
298 // add two more delimters
299 cxstring delim_more[2] = {cx_str("||"), cx_str(";")};
300 cx_strtok_delim(&ctx, delim_more, 2);
301
302 // iterate over the tokens
303 cxstring tok;
304 while(cx_strtok_next(&ctx, &tok)) {
305 // to something with the tokens
306 // be aware that tok is NOT zero-terminated!
307 }
308 ```
309
310 ## Conversion to Numbers
311
312 For each integer type, as well as `float` and `double`, there are functions to convert a UCX string to a value of those types.
313
314 Integer conversion comes in two flavors:
315 ```C
316 int cx_strtoi(AnyStr str, int *output, int base);
317
318 int cx_strtoi_lc(AnyStr str, int *output, int base,
319 const char *groupsep);
320 ```
321
322 The basic variant takes a string of any UCX string type, a pointer to the `output` integer, and the `base` (one of 2, 8, 10, or 16).
323 Conversion is attempted with respect to the specified `base` and respects possible special notations for that base.
324 Hexadecimal numbers may be prefixed with `0x`, `x`, or `#`, and binary numbers may be prefixed with `0b` or `b`.
325
326 The `_lc` versions of the integer conversion functions are equivalent, except that they allow the specification of an
327 array of group separator chars, each of which is simply ignored during conversion.
328 The default group separator for the basic version is a comma `,`.
329
330 The signature for the floating-point conversions is quite similar:
331 ```C
332 int cx_strtof(AnyStr str, float *output);
333
334 int cx_strtof_lc(AnyStr str, float *output,
335 char decsep, const char *groupsep);
336 ```
337
338 The two differences are that the floating-point versions do not support different bases,
339 and the `_lc` variant allows specifying not only an array of group separators,
340 but also the character used for the decimal separator.
341
342 In the basic variant, the group separator is again a comma `,`, and the decimal separator is a dot `.`.
343
344 > The floating-point conversions of UCX 3.1 do not achieve the same precision as standard library implementations
345 > which usually use more sophisticated algorithms.
346 > The precision might increase in future UCX releases,
347 > but until then be aware of slight inaccuracies, in particular when working with `double`.
348 {style="warning"}
349
350 > The UCX string to number conversions are intentionally not considering any locale settings
351 > and are therefore independent of any global state.
352 {style="note"}
353
354 <seealso>
355 <category ref="apidoc">
356 <a href="https://ucx.sourceforge.io/api/string_8h.html">string.h</a>
357 </category>
358 </seealso>
359