From 7aee1bc71c08f2c5b69243cb1ca792c8e7615faa Mon Sep 17 00:00:00 2001 From: Ben Pfaff Date: Sat, 9 Jan 2021 11:24:22 -0800 Subject: [PATCH] string-array: New function string_array_uniq(). --- src/libpspp/string-array.c | 19 +++++++++++++++++++ src/libpspp/string-array.h | 1 + 2 files changed, 20 insertions(+) diff --git a/src/libpspp/string-array.c b/src/libpspp/string-array.c index a22ade6e10..d4badf4638 100644 --- a/src/libpspp/string-array.c +++ b/src/libpspp/string-array.c @@ -234,6 +234,25 @@ string_array_sort (struct string_array *sa) qsort (sa->strings, sa->n, sizeof *sa->strings, compare_strings); } +/* Removes all but one of any series of adjacent duplicate strings in SA. */ +void +string_array_uniq (struct string_array *sa) +{ + if (!sa->n) + return; + + size_t n = 1; + for (size_t i = 1; i < sa->n; i++) + { + char *s = sa->strings[i]; + if (strcmp (sa->strings[n - 1], s)) + sa->strings[n++] = s; + else + free (s); + } + sa->n = n; +} + /* Divides STRING into tokens at DELIMITERS and adds each token to SA. */ void string_array_parse (struct string_array *sa, struct substring string, diff --git a/src/libpspp/string-array.h b/src/libpspp/string-array.h index ecad3326b6..353ddf5018 100644 --- a/src/libpspp/string-array.h +++ b/src/libpspp/string-array.h @@ -61,6 +61,7 @@ void string_array_terminate_null (struct string_array *); void string_array_shrink (struct string_array *); void string_array_sort (struct string_array *); +void string_array_uniq (struct string_array *); void string_array_parse (struct string_array *, struct substring string, struct substring delimiters); -- 2.30.2