feat: (cstr) strtrim, strtriml, strtrimr

This commit is contained in:
thetek 2023-02-11 15:06:47 +01:00
parent e0ab3286a2
commit 66f45c9152
3 changed files with 89 additions and 0 deletions

62
lib/cstr.c Normal file
View File

@ -0,0 +1,62 @@
#include "cstr.h"
#include <ctype.h>
#include <string.h>
/**
* trim whitespace of a cstring (both beginning and end). a null terminator
* will be placed after the last non-whitespace character. this modifies the
* string.
*
* @param str: the string to trim
*
* @return a pointer to the beginning of the trimmed string. the string is not
* copied, and the returned pointer points to somewhere within the
* original string.
*/
char *
strtrim (char *str)
{
strtrimr (str);
return strtriml (str);
}
/**
* trim whitespace of a cstring on the left (beginning of string). the original
* string will be preserved.
*
* @param str: the string to trim
*
* @return a pointer to the beginning of the trimmed string. the string is not
* copied, and the returned pointer points to somewhere within the
* original string.
*/
char *
strtriml (const char *str)
{
while (*str && isspace (*str))
str++;
return str;
}
/**
* trim whitespace of a cstring on the right (end of string). a null terminator
* will be placed after the last non-whitespace character. this modifies the
* string.
*
* @param str: the string to trim
*
* @return the new string length
*/
size_t
strtrimr (char *str)
{
size_t len, i;
i = len = strlen (str);
while (i <= len && isspace (str[i - 1]))
i--;
str[i] = '\0';
return i;
}

10
lib/inc/cstr.h Normal file
View File

@ -0,0 +1,10 @@
#ifndef CUTILS_CSTR_H_
#define CUTILS_CSTR_H_
#include <stddef.h>
char *strtrim (char *str); /* trim whitespace of a cstring (both beginning and end) */
char *strtriml (const char *str); /* trim whitespace of a cstring on the left (beginning of string). */
size_t strtrimr (char *str); /* trim whitespace of a cstring on the right (end of string) */
#endif // CUTILS_CSTR_H_

View File

@ -1,6 +1,9 @@
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cstr.h"
#define CUTILS_DEBUG_TRACE
#include "debug.h"
#include "log.h"
@ -9,6 +12,7 @@ int
main (void)
{
char *ptr;
size_t len;
ptr = malloc ((sizeof *ptr) * 1);
ptr = realloc (ptr, (sizeof *ptr) * 4096);
@ -22,5 +26,18 @@ main (void)
log_print (LOG_LEVEL_DEBUG, "debug! %04.04f\n", 13.37);
log_print_fl (LOG_LEVEL_OK, __FILE__, __LINE__, "file and line\n");
char s[] = " Hello, World!\n ";
len = strtrimr (s);
assert (len == 17);
assert (strlen (s) == 17);
char *sn = strtriml (s);
assert (sn == s + 4);
assert (strlen (sn) == 13);
char s2[] = " Hello, World!\n ";
sn = strtrim (s2);
assert (strlen (s2) == 17);
assert (sn == s2 + 4);
assert (strlen (sn) == 13);
return EXIT_SUCCESS;
}