1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

string.split_nth - return the rest of the string as the last value in the result array

This commit is contained in:
Delyan Angelov 2020-01-24 21:12:36 +02:00 committed by Alexander Medvednikov
parent df2d3a268d
commit 219239eadc
2 changed files with 40 additions and 4 deletions

View File

@ -402,6 +402,12 @@ pub fn (s string) split(delim string) []string {
return s.split_nth(delim, 0)
}
/*
split_nth - splits the string based on the passed `delim` substring.
It returns the first Nth parts. When N=0, return all the splits.
The last returned element has the remainder of the string, even if
the remainder contains more `delim` substrings.
*/
pub fn (s string) split_nth(delim string, nth int) []string {
mut res := []string
mut i := 0
@ -418,6 +424,7 @@ pub fn (s string) split_nth(delim string, nth int) []string {
return res
}
mut start := 0
nth_1 := nth - 1
for i <= s.len {
mut is_delim := s[i] == delim[0]
mut j := 0
@ -425,10 +432,6 @@ pub fn (s string) split_nth(delim string, nth int) []string {
is_delim = is_delim && s[i + j] == delim[j]
j++
}
was_last := nth > 0 && res.len == nth
if was_last {
break
}
last := i == s.len - 1
if is_delim || last {
if !is_delim && last {
@ -438,6 +441,13 @@ pub fn (s string) split_nth(delim string, nth int) []string {
if val.starts_with(delim) {
val = val.right(delim.len)
}
was_last := nth > 0 && res.len == nth_1
if was_last {
res << s.right(start)
break
}
res << val
start = i + delim.len
}

View File

@ -121,6 +121,32 @@ fn test_split_nth() {
assert (e.split_nth(',', 3).len == 3)
}
fn test_split_nth_values() {
line := 'CMD=eprintln(phase=1)'
a0 := line.split_nth('=', 0)
assert a0.len == 3
assert a0[0] == 'CMD'
assert a0[1] == 'eprintln(phase'
assert a0[2] == '1)'
a1 := line.split_nth('=', 1)
assert a1.len == 1
assert a1[0] == 'CMD=eprintln(phase=1)'
a2 := line.split_nth('=', 2)
assert a2.len == 2
assert a2[0] == 'CMD'
assert a2[1] == 'eprintln(phase=1)'
a3 := line.split_nth('=', 3)
assert a3.len == 3
assert a3[0] == 'CMD'
assert a3[1] == 'eprintln(phase'
assert a3[2] == '1)'
}
fn test_split() {
mut s := 'volt/twitch.v:34'
mut vals := s.split(':')