From 5ba99d9302cd86aee99958b71075d5288bb430aa Mon Sep 17 00:00:00 2001 From: Werner Koch Date: Sat, 11 Jun 2016 12:09:48 +0200 Subject: common: New function split_fields. * common/stringhelp.c (split_fields): New. * common/t-stringhelp.c: Include assert.h. (test_split_fields): New. (main): Call test. Signed-off-by: Werner Koch --- common/stringhelp.c | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) (limited to 'common/stringhelp.c') diff --git a/common/stringhelp.c b/common/stringhelp.c index 8b47a1c7b..0e96c9e54 100644 --- a/common/stringhelp.c +++ b/common/stringhelp.c @@ -1329,6 +1329,44 @@ strtokenize (const char *string, const char *delim) } +/* Split a string into space delimited fields and remove leading and + * trailing spaces from each field. A pointer to each field is stored + * in ARRAY. Stop splitting at ARRAYSIZE fields. The function + * modifies STRING. The number of parsed fields is returned. + * Example: + * + * char *fields[2]; + * if (split_fields (string, fields, DIM (fields)) < 2) + * return // Not enough args. + * foo (fields[0]); + * foo (fields[1]); + */ +int +split_fields (char *string, char **array, int arraysize) +{ + int n = 0; + char *p, *pend; + + for (p = string; *p == ' '; p++) + ; + do + { + if (n == arraysize) + break; + array[n++] = p; + pend = strchr (p, ' '); + if (!pend) + break; + *pend++ = 0; + for (p = pend; *p == ' '; p++) + ; + } + while (*p); + + return n; +} + + /* Version number parsing. */ -- cgit