Update str.c and README based on AI code review
This commit is contained in:
parent
8915ce7735
commit
1432c00d54
1 changed files with 19 additions and 28 deletions
|
|
@ -5,6 +5,7 @@
|
||||||
#include <ctype.h>
|
#include <ctype.h>
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
/* Functions */
|
/* Functions */
|
||||||
|
|
||||||
|
|
@ -59,44 +60,34 @@ void str_title(const char *s, char *w) {
|
||||||
*w = '\0';
|
*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) {
|
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
|
bool strip_chars[256] = {0};
|
||||||
if (chars == NULL) {
|
const unsigned char *p = (const unsigned char *)s;
|
||||||
// If chars is NULL, strip whitespace
|
size_t length = 0;
|
||||||
|
|
||||||
|
// Build lookup table
|
||||||
|
if (!chars) {
|
||||||
|
// Strip standard whitespace
|
||||||
strip_chars[' '] = true;
|
strip_chars[' '] = true;
|
||||||
strip_chars['\t'] = true;
|
strip_chars['\t'] = true;
|
||||||
strip_chars['\n'] = true;
|
strip_chars['\n'] = true;
|
||||||
} else {
|
} else {
|
||||||
// Otherwise, strip specified characters
|
for (; *chars; chars++)
|
||||||
while (*chars) {
|
|
||||||
strip_chars[(unsigned char)*chars] = true;
|
strip_chars[(unsigned char)*chars] = true;
|
||||||
chars++;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy s to w
|
// Find string length and last non-stripped character
|
||||||
const char *src = s;
|
while (*p) p++;
|
||||||
char *dst = w;
|
while (p > (const unsigned char *)s && strip_chars[*(p-1)])
|
||||||
while (*src) {
|
p--;
|
||||||
*dst++ = *src++;
|
|
||||||
}
|
|
||||||
*dst = '\0';
|
|
||||||
|
|
||||||
if (dst > w) {
|
// Calculate length and copy
|
||||||
dst--;
|
length = p - (const unsigned char *)s;
|
||||||
while (dst >= w && strip_chars[(unsigned char)*dst]) {
|
memcpy(w, s, length);
|
||||||
dst--;
|
w[length] = '\0';
|
||||||
}
|
|
||||||
*(dst + 1) = '\0';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue