Skip to content

Commit

Permalink
gstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
snail007 committed Dec 21, 2023
1 parent 6d414e7 commit 22a8f3b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
14 changes: 14 additions & 0 deletions util/strings/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,17 @@ func HasSuffixAny(str string, suffix ...string) bool {
func HasHTTPPrefix(str string) bool {
return HasPrefixAny(strings.ToLower(str), "http://", "https://")
}

// Replace str from a list of old, new string
// pairs. Replacements are performed in the order they appear in the
// target string, without overlapping matches. The old string
// comparisons are done in argument order.
//
// Replace panics if given an odd number of oldNew arguments.
func Replace(str string, oldNew ...string) string {
if len(oldNew) == 0 {
return str
}
r := strings.NewReplacer(oldNew...)
return r.Replace(str)
}
20 changes: 20 additions & 0 deletions util/strings/strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,23 @@ func TestHasSuffix(t *testing.T) {
assert.True(t, HasSuffixAny("a.txt", ".log", ".txt"))
assert.False(t, HasSuffixAny("a.log", ".log1", ".txt1"))
}

func TestReplace(t *testing.T) {
testCases := []struct {
input string
oldNew []string
expected string
}{
{"Hello, world!", []string{"world", "Go"}, "Hello, Go!"},
{"foo bar foo", []string{"foo", "baz", "bar", "qux"}, "baz qux baz"},
{"abc", []string{"x", "y"}, "abc"}, // No replacement
{"", []string{}, ""}, // Empty string and no replacements
}

for _, testCase := range testCases {
result := Replace(testCase.input, testCase.oldNew...)
if result != testCase.expected {
t.Errorf("For input '%s' with replacements %v, expected '%s', but got '%s'", testCase.input, testCase.oldNew, testCase.expected, result)
}
}
}

0 comments on commit 22a8f3b

Please sign in to comment.