2021-02-07 22:31:04 +03:00
|
|
|
### Length prefixed string
|
2020-12-28 06:18:18 +03:00
|
|
|
|
|
|
|
Length prefixed C strings, length is at the start of the allocated memory
|
|
|
|
|
|
|
|
e.g :
|
|
|
|
-----------------------------------------------
|
|
|
|
| 0 | 0 | 0 | 4 | 'T' | 'E' | 'S' | 'T' | '\0'|
|
|
|
|
-----------------------------------------------
|
|
|
|
^
|
|
|
|
return
|
|
|
|
User can keep pointer to first character, so it's like C style strings with
|
2021-02-03 08:09:50 +03:00
|
|
|
additional functionality.
|
2020-12-28 06:18:18 +03:00
|
|
|
|
2021-02-07 22:31:04 +03:00
|
|
|
### Pros
|
2020-12-28 06:18:18 +03:00
|
|
|
- User gets a null terminated `char*`, so it still works with c style string
|
|
|
|
functions, e.g printf, strcmp.
|
2021-02-07 22:31:04 +03:00
|
|
|
- This implementation is mostly about avoiding strlen() cost.
|
2021-02-06 10:19:31 +03:00
|
|
|
Provides a few more functions to make easier create/append/trim/substring
|
2020-12-28 06:18:18 +03:00
|
|
|
operations.
|
|
|
|
|
2021-02-07 22:31:04 +03:00
|
|
|
### Cons
|
2021-02-06 10:19:31 +03:00
|
|
|
- 4 bytes fixed overhead per string and max string size is ~4gb.
|
2020-12-28 06:18:18 +03:00
|
|
|
- When you create/set/append a string, new memory is allocated. If you are
|
|
|
|
modifying strings a lot, consider using buffer-like implementation for that if
|
2021-02-06 10:19:31 +03:00
|
|
|
performance is critical for your use-case. I modify strings rarely but read
|
2021-02-05 16:35:10 +03:00
|
|
|
a lot (copy/move etc.).
|
|
|
|
|
2020-12-28 06:18:18 +03:00
|
|
|
```c
|
|
|
|
#include "sc_str.h"
|
|
|
|
|
|
|
|
#include <stdio.h>
|
|
|
|
|
|
|
|
int main(int argc, char *argv[])
|
|
|
|
{
|
|
|
|
char* s1;
|
|
|
|
|
2021-02-04 11:17:43 +03:00
|
|
|
s1 = sc_str_create("*-hello-*");
|
2021-02-05 16:35:10 +03:00
|
|
|
printf("%s \n", s1); // prints *-hello-*
|
2020-12-28 06:18:18 +03:00
|
|
|
|
|
|
|
sc_str_trim(&s1, "*-");
|
2021-02-04 11:17:43 +03:00
|
|
|
printf("%s \n", s1); // prints hello
|
|
|
|
|
|
|
|
sc_str_append_fmt(&s1, "%d", 2);
|
|
|
|
printf("%s \n", s1); // prints hello2
|
2020-12-28 06:18:18 +03:00
|
|
|
|
2021-02-04 11:17:43 +03:00
|
|
|
sc_str_replace(&s1, "2", " world!");
|
|
|
|
printf("%s \n", s1); // prints hello world!
|
|
|
|
|
|
|
|
sc_str_substring(&s1, 0, 5);
|
|
|
|
printf("%s \n", s1); // prints hello
|
2020-12-28 06:18:18 +03:00
|
|
|
|
|
|
|
sc_str_destroy(s1);
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
2021-02-04 11:17:43 +03:00
|
|
|
|
2020-12-28 06:18:18 +03:00
|
|
|
```
|