Improve str_trim_words and add tests

- Change argument and return value to `const char *`, as the string is not modified by this function.
- Use our own `str_isspace` instead of standard library `isspace`.
- Always trim leading whitespace to correctly handle inputs with leading whitespace.
This commit is contained in:
Robert Müller 2022-09-28 13:53:05 +02:00
parent e98728f8f0
commit ce145cfa4e
3 changed files with 30 additions and 3 deletions

View file

@ -2648,11 +2648,13 @@ int str_format(char *buffer, int buffer_size, const char *format, ...)
return str_utf8_fix_truncation(buffer);
}
char *str_trim_words(char *str, int words)
const char *str_trim_words(const char *str, int words)
{
while(*str && str_isspace(*str))
str++;
while(words && *str)
{
if(isspace(*str) && !isspace(*(str + 1)))
if(str_isspace(*str) && !str_isspace(*(str + 1)))
words--;
str++;
}

View file

@ -1246,8 +1246,9 @@ int str_format(char *buffer, int buffer_size, const char *format, ...)
* @return Trimmed string
*
* @remark The strings are treated as zero-terminated strings.
* @remark Leading whitespace is always trimmed.
*/
char *str_trim_words(char *str, int words);
const char *str_trim_words(const char *str, int words);
/**
* Check whether string has ASCII control characters.

View file

@ -374,6 +374,30 @@ TEST(Str, FormatTruncate)
EXPECT_STREQ(aBuf, "DDNet最好了");
}
TEST(Str, TrimWords)
{
const char *pStr1 = "aa bb ccc dddd eeeee";
EXPECT_STREQ(str_trim_words(pStr1, 0), "aa bb ccc dddd eeeee");
EXPECT_STREQ(str_trim_words(pStr1, 1), "bb ccc dddd eeeee");
EXPECT_STREQ(str_trim_words(pStr1, 2), "ccc dddd eeeee");
EXPECT_STREQ(str_trim_words(pStr1, 3), "dddd eeeee");
EXPECT_STREQ(str_trim_words(pStr1, 4), "eeeee");
EXPECT_STREQ(str_trim_words(pStr1, 5), "");
EXPECT_STREQ(str_trim_words(pStr1, 100), "");
const char *pStr2 = " aaa bb ";
EXPECT_STREQ(str_trim_words(pStr2, 0), "aaa bb ");
EXPECT_STREQ(str_trim_words(pStr2, 1), "bb ");
EXPECT_STREQ(str_trim_words(pStr2, 2), "");
EXPECT_STREQ(str_trim_words(pStr2, 100), "");
const char *pStr3 = "\n\naa bb\t\tccc\r\n\r\ndddd";
EXPECT_STREQ(str_trim_words(pStr3, 0), "aa bb\t\tccc\r\n\r\ndddd");
EXPECT_STREQ(str_trim_words(pStr3, 1), "bb\t\tccc\r\n\r\ndddd");
EXPECT_STREQ(str_trim_words(pStr3, 2), "ccc\r\n\r\ndddd");
EXPECT_STREQ(str_trim_words(pStr3, 3), "dddd");
EXPECT_STREQ(str_trim_words(pStr3, 4), "");
EXPECT_STREQ(str_trim_words(pStr3, 100), "");
}
TEST(Str, CopyNum)
{
const char *pFoo = "Foobaré";