Update str.c and README based on AI code review

This commit is contained in:
Owen Dorweiler 2025-03-26 17:55:52 -04:00
commit 1432c00d54

View file

@ -5,6 +5,7 @@
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
/* Functions */
@ -59,44 +60,34 @@ void str_title(const char *s, char *w) {
*w = '\0';
}
/**
* Strip characters from back of string (if present).
* @param s String to strip
* @param chars Characters to strip (if NULL, then all whitespace)
* @param w Pointer to buffer that holds result of strip
**/
void str_rstrip(const char *s, const char *chars, char *w) {
bool strip_chars[256] = {0};
// Safety checks
if (!s || !w) return;
// Create the lookup table
if (chars == NULL) {
// If chars is NULL, strip whitespace
strip_chars[' '] = true;
bool strip_chars[256] = {0};
const unsigned char *p = (const unsigned char *)s;
size_t length = 0;
// Build lookup table
if (!chars) {
// Strip standard whitespace
strip_chars[' '] = true;
strip_chars['\t'] = true;
strip_chars['\n'] = true;
} else {
// Otherwise, strip specified characters
while (*chars) {
for (; *chars; chars++)
strip_chars[(unsigned char)*chars] = true;
chars++;
}
}
// Copy s to w
const char *src = s;
char *dst = w;
while (*src) {
*dst++ = *src++;
}
*dst = '\0';
// Find string length and last non-stripped character
while (*p) p++;
while (p > (const unsigned char *)s && strip_chars[*(p-1)])
p--;
if (dst > w) {
dst--;
while (dst >= w && strip_chars[(unsigned char)*dst]) {
dst--;
}
*(dst + 1) = '\0';
}
// Calculate length and copy
length = p - (const unsigned char *)s;
memcpy(w, s, length);
w[length] = '\0';
}
/**