From 402be3d385610cb5b7d83da738f84da3f3b0c380 Mon Sep 17 00:00:00 2001 From: Nikitin Aleksandr Date: Thu, 14 Nov 2024 14:49:44 +0300 Subject: [PATCH] =?UTF-8?q?=D1=81=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB=20msg.Pars?= =?UTF-8?q?eMode=20=3D=20"HTML"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- micro/microfunctions.go | 15 +++++++++++++++ micro/microfunctions_test.go | 22 ++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/micro/microfunctions.go b/micro/microfunctions.go index 1ac128cb..82517254 100644 --- a/micro/microfunctions.go +++ b/micro/microfunctions.go @@ -1215,3 +1215,18 @@ func MassFrom_Map[C constraints.Ordered, V any](Map map[C]V) []V { return Otvet } + +// Substring - take at most last n characters, from start index +func Substring(input string, StartIndex int, length int) string { + asRunes := []rune(input) + + if StartIndex >= len(asRunes) { + return "" + } + + if StartIndex+length > len(asRunes) { + length = len(asRunes) - StartIndex + } + + return string(asRunes[StartIndex : StartIndex+length]) +} diff --git a/micro/microfunctions_test.go b/micro/microfunctions_test.go index 479fac1d..1717e943 100644 --- a/micro/microfunctions_test.go +++ b/micro/microfunctions_test.go @@ -1206,3 +1206,25 @@ func TestStringDateTime(t *testing.T) { t.Errorf("Test case 2 failed. Expected: %s, Got: %s", expectedResult2, result2) } } + +func TestSubstring(t *testing.T) { + tests := []struct { + input string + startIndex int + length int + expected string + description string + }{ + {"hello", 0, 2, "he", "Getting the first 2 characters"}, + {"world", 2, 3, "rld", "Getting characters from index 2 to 4"}, + {"test", 5, 2, "", "Start index beyond the length of the string"}, + {"", 0, 2, "", "Empty input string"}, + } + + for _, test := range tests { + result := Substring(test.input, test.startIndex, test.length) + if result != test.expected { + t.Errorf("Test case failed: %s. Expected: %s, but got: %s", test.description, test.expected, result) + } + } +}