Minor cleanup.

This commit is contained in:
Simon Forman 2023-02-01 18:35:11 -08:00
parent 6b87e46e00
commit 66cbbac1cc
1 changed files with 47 additions and 37 deletions

View File

@ -5,54 +5,64 @@
const char *BLANKS = " \t"; const char *BLANKS = " \t";
const char *TEXT = "hi there fr [[] ie]nd] [] 23 "; const char *TEXT = " 23 [dup *] i hi there fr [[] ie]nd] [] 23 ";
/* 01234567890123456789
^ ^
*/
char * char *
trim_leading_blanks(char *str) trim_leading_blanks(char *str)
{ {
size_t offset = strspn(str, BLANKS); size_t offset = strspn(str, BLANKS);
if (offset == strlen(str)) { return (offset == strlen(str)) ? NULL : (str + offset);
/* All blanks. */
return NULL;
}
return str + offset;
} }
int int
main(void) main(void)
{ {
char *rest, *text, *snip; char *rest, *text, *snip;
ptrdiff_t diff; ptrdiff_t diff;
text = trim_leading_blanks((char *)TEXT); text = trim_leading_blanks((char *)TEXT);
rest = strpbrk(text, " []"); if (NULL == text) {
while (NULL != rest) { /* All blanks. */
/* How many chars have we got? */ return 1;
diff = rest - text; }
if (diff) { rest = strpbrk(text, " []");
/* Allocate space and copy out the substring. */ /*
snip = (char *)GC_malloc(diff + 1); rest now points to a space or '[' or ']' after a term,
strncat(snip, text, diff); -or- it is NULL if the rest of the string is a single term
printf("%s\n", snip); with no spaces nor brackets.
} */
/* The next char is a space or '[' or ']'. */ while (NULL != rest) {
if ('[' == rest[0] || ']' == rest[0]) {
printf("%c\n", rest[0]); /* How many chars have we got? */
} diff = rest - text;
/*
/* */ diff can be zero when there is more than one space in
text = trim_leading_blanks(++rest); a sequence in the input string. This won't happen on
/*printf(">>>%s\n\n", text);*/ the first iteration but it can on later iterations.
*/
/* calling strpbrk on NULL caused segfault! */
rest = (NULL != text) ? strpbrk(text, " []") : text; if (diff) {
/* Allocate space and copy out the substring. */
snip = (char *)GC_malloc(diff + 1);
strncat(snip, text, diff);
printf("%s\n", snip);
}
/* The next char is a space or '[' or ']'. */
if ('[' == rest[0] || ']' == rest[0]) {
printf("%c\n", rest[0]);
}
text = trim_leading_blanks(++rest);
/* calling strpbrk on NULL caused segfault! */
rest = (NULL != text) ? strpbrk(text, " []") : text;
}
if (text) {
printf("%s\n", text);
} }
if (text) {
printf("%s\n", text);
}
} }