From 6f550ebbdc41cce3c1fd746c27aa4ff044507762 Mon Sep 17 00:00:00 2001 From: JalonSolov Date: Tue, 16 Mar 2021 13:45:27 -0400 Subject: [PATCH] string: fix fields method when no whitespace (#9326) --- vlib/builtin/string.v | 12 +++++++----- vlib/builtin/string_test.v | 3 ++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index 823f4220fb..cc6da37970 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -1618,26 +1618,28 @@ pub fn (s string) repeat(count int) string { pub fn (s string) fields() []string { mut res := []string{} mut word_start := 0 - mut word_end := 0 + mut word_len := 0 mut is_in_word := false mut is_space := false for i, c in s { is_space = c in [` `, `\t`, `\n`] + if !is_space { + word_len++ + } if !is_in_word && !is_space { word_start = i is_in_word = true continue } if is_space && is_in_word { - word_end = i - res << s[word_start..word_end] + res << s[word_start..word_start + word_len] is_in_word = false - word_end = 0 + word_len = 0 word_start = 0 continue } } - if is_in_word && word_start > 0 { + if is_in_word && word_len > 0 { // collect the remainder word at the end res << s[word_start..s.len] } diff --git a/vlib/builtin/string_test.v b/vlib/builtin/string_test.v index 66f949d522..a23047c5b9 100644 --- a/vlib/builtin/string_test.v +++ b/vlib/builtin/string_test.v @@ -915,10 +915,11 @@ fn test_sorter() { assert arr[2].i == 102 } -fn test_split_by_whitespace() { +fn test_fields() { assert 'a bcde'.fields() == ['a', 'bcde'] assert ' sss \t ssss '.fields() == ['sss', 'ssss'] assert '\n xyz \t abc def'.fields() == ['xyz', 'abc', 'def'] + assert 'hello'.fields() == ['hello'] assert ''.fields() == [] }