From 1432c00d549460442a794bebcfcf328c1ba17c78 Mon Sep 17 00:00:00 2001 From: Owen Dorweiler Date: Wed, 26 Mar 2025 17:55:52 -0400 Subject: [PATCH] Update str.c and README based on AI code review --- homework06/str.c | 49 ++++++++++++++++++++---------------------------- 1 file changed, 20 insertions(+), 29 deletions(-) diff --git a/homework06/str.c b/homework06/str.c index e4e5fb3..68d2d08 100644 --- a/homework06/str.c +++ b/homework06/str.c @@ -5,6 +5,7 @@ #include #include #include +#include /* 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'; } /**