From f213180533b5e4562eefd7a071196cb43444d1a2 Mon Sep 17 00:00:00 2001 From: Michael Schupikov Date: Sun, 8 Jan 2017 20:30:16 +0100 Subject: [PATCH] strip_whitespace(): Improve and simplify (#1034) Now strip_whitespace() also strips the unnecessary whitespace between words in the string. That fixes issues reading the configuration file if too much space is included between tokens. --- common/stringop.c | 40 +++++++++++++++++++++++++--------------- include/stringop.h | 2 +- sway/config.c | 2 +- 3 files changed, 27 insertions(+), 17 deletions(-) diff --git a/common/stringop.c b/common/stringop.c index 432bee7ff..ad128e52d 100644 --- a/common/stringop.c +++ b/common/stringop.c @@ -10,22 +10,32 @@ const char whitespace[] = " \f\n\r\t\v"; -char *strip_whitespace(char *_str) { - if (*_str == '\0') - return _str; - char *strold = _str; - while (*_str == ' ' || *_str == '\t') { - _str++; +/**************************************************************************//** + * + * \brief Strips the whitespace in front and rear of the string. If whitespace + * is found in the middle of the string, all but one space is removed + * between words. + * + * \param str Pointer to the char string that should be stripped. The string + * is modified. If NULL is passed, no operation is performed. + * + ******************************************************************************/ +void strip_whitespace(char * restrict const str) +{ + if (NULL != str) { + unsigned int count = 0u; + for (unsigned int index = 0u; str[index]; ++index) { + if (' ' != str[index] && '\t' != str[index]) { + str[count++] = str[index]; + } else if(0u < count && ' ' != str[count-1u] && '\t' != str[count-1u]) { + str[count++] = ' '; + } + } + str[count] = '\0'; + if (0u < count && (' ' == str[count-1u] || '\t' == str[count-1u])) { + str[count-1u] = '\0'; + } } - char *str = strdup(_str); - free(strold); - int i; - for (i = 0; str[i] != '\0'; ++i); - do { - i--; - } while (i >= 0 && (str[i] == ' ' || str[i] == '\t')); - str[i + 1] = '\0'; - return str; } void strip_quotes(char *str) { diff --git a/include/stringop.h b/include/stringop.h index 7c29a745e..2555babfb 100644 --- a/include/stringop.h +++ b/include/stringop.h @@ -10,7 +10,7 @@ extern int setenv(const char *, const char *, int); // array of whitespace characters to use for delims extern const char whitespace[]; -char *strip_whitespace(char *str); +void strip_whitespace(char *str); char *strip_comments(char *str); void strip_quotes(char *str); diff --git a/sway/config.c b/sway/config.c index 9e758c903..f182fc944 100644 --- a/sway/config.c +++ b/sway/config.c @@ -632,7 +632,7 @@ bool read_config(FILE *file, struct sway_config *config) { continue; } line_number++; - line = strip_whitespace(line); + strip_whitespace(line); if (line[0] == '#') { free(line); continue;