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() == [] }