From b622dca9158d1ff870ff71ad89f44d7a655b02ce Mon Sep 17 00:00:00 2001 From: katekyy <74244551+katekyy@users.noreply.github.com> Date: Sat, 29 Jul 2023 23:12:51 +0200 Subject: [PATCH] builtin: fix split_nth() and rsplit_nth() on an empty delimeter (#19005) --- vlib/builtin/string.v | 4 ++-- vlib/builtin/string_test.v | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index 02ae63bda3..02c67c4788 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -865,7 +865,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[i..] + res << s[i - 1..] break } res << ch.ascii_str() @@ -938,7 +938,7 @@ pub fn (s string) rsplit_nth(delim string, nth int) []string { 0 { for i >= 0 { if nth > 0 && res.len == nth - 1 { - res << s[..i] + res << s[..i + 1] break } res << s[i].ascii_str() diff --git a/vlib/builtin/string_test.v b/vlib/builtin/string_test.v index d17f40fec8..1882166b2c 100644 --- a/vlib/builtin/string_test.v +++ b/vlib/builtin/string_test.v @@ -183,6 +183,15 @@ fn test_split_nth() { assert e.split_nth(',,', 3).len == 3 assert e.split_nth(',', -1).len == 12 assert e.split_nth(',', 3).len == 3 + f := '1:2:3' + assert f.split_nth(':', 2) == ['1', '2:3'] + assert f.rsplit_nth(':', 2) == ['3', '1:2'] + g := '123' + assert g.split_nth('', 2) == ['1', '23'] + assert g.rsplit_nth('', 2) == ['3', '12'] + h := '' + assert h.split_nth('', 2) == [] + assert h.rsplit_nth('', 2) == [] } fn test_rsplit_nth() {