mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
string: fix fields method when no whitespace (#9326)
This commit is contained in:
parent
98c611d5d9
commit
6f550ebbdc
@ -1618,26 +1618,28 @@ pub fn (s string) repeat(count int) string {
|
|||||||
pub fn (s string) fields() []string {
|
pub fn (s string) fields() []string {
|
||||||
mut res := []string{}
|
mut res := []string{}
|
||||||
mut word_start := 0
|
mut word_start := 0
|
||||||
mut word_end := 0
|
mut word_len := 0
|
||||||
mut is_in_word := false
|
mut is_in_word := false
|
||||||
mut is_space := false
|
mut is_space := false
|
||||||
for i, c in s {
|
for i, c in s {
|
||||||
is_space = c in [` `, `\t`, `\n`]
|
is_space = c in [` `, `\t`, `\n`]
|
||||||
|
if !is_space {
|
||||||
|
word_len++
|
||||||
|
}
|
||||||
if !is_in_word && !is_space {
|
if !is_in_word && !is_space {
|
||||||
word_start = i
|
word_start = i
|
||||||
is_in_word = true
|
is_in_word = true
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if is_space && is_in_word {
|
if is_space && is_in_word {
|
||||||
word_end = i
|
res << s[word_start..word_start + word_len]
|
||||||
res << s[word_start..word_end]
|
|
||||||
is_in_word = false
|
is_in_word = false
|
||||||
word_end = 0
|
word_len = 0
|
||||||
word_start = 0
|
word_start = 0
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if is_in_word && word_start > 0 {
|
if is_in_word && word_len > 0 {
|
||||||
// collect the remainder word at the end
|
// collect the remainder word at the end
|
||||||
res << s[word_start..s.len]
|
res << s[word_start..s.len]
|
||||||
}
|
}
|
||||||
|
@ -915,10 +915,11 @@ fn test_sorter() {
|
|||||||
assert arr[2].i == 102
|
assert arr[2].i == 102
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_split_by_whitespace() {
|
fn test_fields() {
|
||||||
assert 'a bcde'.fields() == ['a', 'bcde']
|
assert 'a bcde'.fields() == ['a', 'bcde']
|
||||||
assert ' sss \t ssss '.fields() == ['sss', 'ssss']
|
assert ' sss \t ssss '.fields() == ['sss', 'ssss']
|
||||||
assert '\n xyz \t abc def'.fields() == ['xyz', 'abc', 'def']
|
assert '\n xyz \t abc def'.fields() == ['xyz', 'abc', 'def']
|
||||||
|
assert 'hello'.fields() == ['hello']
|
||||||
assert ''.fields() == []
|
assert ''.fields() == []
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user