string: fix fields method when no whitespace (#9326)

pull/9332/head
JalonSolov 2021-03-16 13:45:27 -04:00 committed by GitHub
parent 98c611d5d9
commit 6f550ebbdc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 6 deletions

View File

@ -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]
}

View File

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