plstr is a small library for C that implements some of Python’s string methods. The implemented Python methods are some I have been always missing when using C, or the C equivalent of the Python method has been painful to work with (strtok).
The source can be found at the projects GitHub page, and it includes pre-built documentation and examples. Currently there is a example for every function. All the functions, except for those for internal use are prefixed with pl_, so not to conflict with anything else. A lot of the functions will also allocate memory for the returned results, so a lot of the returned variables needs to be freed after use. It is noted in the documentation if the returned variable needs to be freed.
The reason for doing it this way is to reduce the code I have to write for other projects since the function will handle everything, and I also think this is safer. When the function is responsible for allocating memory it is easier to be sure that the correct amount of memory has been allocated, and I won’t make a mistake by passing a buffer that is too small. Below is a example of the pl_split function, that splits up a string (think strtok):
Example - Split string
Below is a example on how to use the split function. The method will split the string into several sub strings
#include "plstr.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
char the_string[] = "This is a short string.";
char **splitted;
int size;
splitted = pl_split(the_string, " ", &size);
if (splitted != NULL) {
int i;
printf("The size is %d\n", size);
for (i = 0; i < size; i++) {
printf("splitted[%d] = %s\n", i, splitted[i]);
}
for (i = 0; i < size; i++) {
free(splitted[i]);
}
free(splitted);
}
return 0;
}
Output
The size is 5
splitted[0] = This
splitted[1] = is
splitted[2] = a
splitted[3] = short
splitted[4] = string.
Example - slice
#include "plstr.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
char the_string[] = "subdermatoglyphic";
char *sliced;
sliced = pl_slice(the_string, 3, 10);
if (sliced != NULL) {
printf("the_string: %s\nsliced 3, 10: %s\n", the_string, sliced);
free(sliced);
}
sliced = pl_slice(the_string, 0, -10);
if (sliced != NULL) {
printf("sliced 0,-10: %s\n", sliced);
free(sliced);
}
return 0;
}
Output
the_string: subdermatoglyphic
sliced 3, 10: dermato
sliced 0,-10: subderm