From da8c963b7ab5da8cc25f04492503514614a407e0 Mon Sep 17 00:00:00 2001 From: Andreas Schulte Date: Wed, 25 Oct 2023 22:48:39 +0200 Subject: [PATCH] + RemoveLeadingStrings --- strings.go | 16 ++++++++++++++++ strings_test.go | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/strings.go b/strings.go index 14757fe..80bd6e5 100644 --- a/strings.go +++ b/strings.go @@ -52,6 +52,22 @@ func RemoveDoubledStrings(s string, target string) string { ) } +// RemoveLeadingStrings removes all leading occurrences of target in s +func RemoveLeadingStrings(s string, target string) string { + lenS := len(s) + lenTarget := len(target) + + if lenS < lenTarget { + return s + } + + if s[:lenTarget] != target { + return s + } + + return RemoveLeadingStrings(s[lenTarget:], target) +} + // SanitizeStringWithWhitelist cleans s by all substrings which do not occur in whitelist func SanitizeStringWithWhitelist(s string, whitelist map[string]string) string { sanitizedString := "" diff --git a/strings_test.go b/strings_test.go index 3a4f088..fef294f 100644 --- a/strings_test.go +++ b/strings_test.go @@ -1,6 +1,8 @@ package utils -import "testing" +import ( + "testing" +) func TestFirstCharacterToUppercase(t *testing.T) { data := map[string]string{ @@ -56,6 +58,36 @@ func TestRemoveDoubledStrings(t *testing.T) { } } +func TestRemoveLeadingStrings(t *testing.T) { + data := map[string]string{ + "": "", + ".": "", + "...Jahr 2022... die überleben wollen...": "Jahr 2022... die überleben wollen...", + } + + for d, expectedResult := range data { + result := RemoveLeadingStrings(d, ".") + if result != expectedResult { + t.Errorf("\ngot: %q\nwanted: %q\nfor: %q", result, expectedResult, d) + } + } + + data = map[string]string{ + "": "", + ".": ".", + "..": "..", + "...": "", + "....": ".", + } + + for d, expectedResult := range data { + result := RemoveLeadingStrings(d, "...") + if result != expectedResult { + t.Errorf("\ngot: %q\nwanted: %q\nfor: %q", result, expectedResult, d) + } + } +} + func TestSanitizeStringWithWhitelist(t *testing.T) { whitelistedChars := []string{ ".", "-",