From 219239eadc3d0a3c6650ab0950cc52532648bffd Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Fri, 24 Jan 2020 21:12:36 +0200 Subject: [PATCH] string.split_nth - return the rest of the string as the last value in the result array --- vlib/builtin/string.v | 18 ++++++++++++++---- vlib/builtin/string_test.v | 26 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index 20f38ab9c1..a7c1c733b4 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -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 } diff --git a/vlib/builtin/string_test.v b/vlib/builtin/string_test.v index b2fbbd0acc..d8dc1becfe 100644 --- a/vlib/builtin/string_test.v +++ b/vlib/builtin/string_test.v @@ -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(':')