I was looking for a qucik trim function for non-null terminated strings in C. I came up with below solution which worked for me:
#include <ctype.h> /* for isspace */
#include <stddef.h> /* for size_t */
int memtrim(const char *mem, size_t size, const char **begin, const char **end)
{
const char *temp_begin;
const char *temp_end;
if (begin == NULL) {
begin = &temp_begin;
}
if (end == NULL) {
end = &temp_end;
}
*begin = mem;
*end = mem + size;
for(; *end > *begin && isspace((unsigned char)*(*end-1)); (*end)--);
for(; *begin < *end && isspace((unsigned char)**begin); (*begin)++);
return *end == *begin;
}
What it does (in that order):
- Trim from right, store it to the
end
if provided. - Trim from left, store it to the
begin
if provided. - Return true if all characters are whitespace.
Usage:
- Providing the chunk
mem
as NULL is undefined behavior. - If you need both left and right trim, provide both
begin
andend
. - If you need just right trim, provide just
end
(passbegin
asNULL
). - If you need just left trim, provide just
begin
(passend
asNULL
). However, you need to check return value as well to see if the chunk consists of all whitespace characters, because in this case begin will not be modified. This behavior can be easily reversed by changing order of for loops. - Address of the chunk itself
mem
can be provided asbegin
. This may be useful if you are working on a pointer that you don't own, therefore don't care about its address to free later.