diff --git a/cmd/tools/vrepl.v b/cmd/tools/vrepl.v index cf5780f58b..84a90f351b 100644 --- a/cmd/tools/vrepl.v +++ b/cmd/tools/vrepl.v @@ -301,7 +301,7 @@ fn run_repl(workdir string, vrepl_prefix string) { } fn print_output(s os.Result) { - lines := s.output.trim_right('\n\r').split('\n') + lines := s.output.trim_right('\n\r').split_into_lines() for line in lines { if line.contains('.vrepl_temp.v:') { // Hide the temporary file name diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index dd9237bfcd..7d221e3035 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -484,7 +484,7 @@ pub fn (s string) split_nth(delim string, nth int) []string { i = 1 for ch in s { if nth > 0 && i >= nth { - res << s.substr(i, s.len) + res << s.right(i) break } res << ch.str() @@ -493,39 +493,30 @@ pub fn (s string) split_nth(delim string, nth int) []string { return res } mut start := 0 - nth_1 := nth - 1 + // Take the left part for each delimiter occurence for i <= s.len { - mut is_delim := unsafe {s.str[i] == delim.str[0]} - mut j := 0 - for is_delim && j < delim.len { - is_delim = is_delim && unsafe {s.str[i + j] == delim.str[j]} - j++ - } - last := i == s.len - 1 - if is_delim || last { - if !is_delim && last { - i++ - } - mut val := s.substr(start, i) - if val.starts_with(delim) { - val = val.right(delim.len) - } - was_last := nth > 0 && res.len == nth_1 + is_delim := i + delim.len <= s.len && s.substr(i, i + delim.len) == delim + if is_delim { + val := s.substr(start, i) + was_last := nth > 0 && res.len == nth - 1 if was_last { - res << s.right(start) break } res << val start = i + delim.len + i = start + } else { + i++ } - i++ } - if s.ends_with(delim) && (nth < 1 || res.len < nth) { - res << '' + // Then the remaining right part of the string + if nth < 1 || res.len < nth { + res << s.right(start) } return res } + pub fn (s string) split_into_lines() []string { mut res := []string{} if s.len == 0 { diff --git a/vlib/builtin/string_test.v b/vlib/builtin/string_test.v index 324f7384eb..24eff12fd4 100644 --- a/vlib/builtin/string_test.v +++ b/vlib/builtin/string_test.v @@ -138,8 +138,8 @@ fn test_split_nth() { assert (d.split_nth(',', -1).len == 2) assert (d.split_nth(',', 3).len == 2) e := ",,,0,,,,,a,,b," - // assert (e.split(',,').len == 5) - // assert (e.split_nth(',,', 3).len == 2) + assert (e.split(',,').len == 5) + assert (e.split_nth(',,', 3).len == 3) assert (e.split_nth(',', -1).len == 12) assert (e.split_nth(',', 3).len == 3) } @@ -213,6 +213,12 @@ fn test_split() { assert a[4] == 'o' assert a[5] == 'm' assert a[6] == 'e' + // ///////// + s = 'wavy turquoise bags' + vals = s.split(' bags') + assert vals.len == 2 + assert vals[0] == 'wavy turquoise' + assert vals[1] == '' } fn test_trim_space() {