From f5784b0f4612a7a28e456bd2a86b7e0488a3e55c Mon Sep 17 00:00:00 2001 From: dudaodong Date: Wed, 10 May 2023 10:03:13 +0800 Subject: [PATCH] feat: add ReplaceByMap --- strutil/string.go | 11 +++++++++++ strutil/string_example_test.go | 14 ++++++++++++++ strutil/string_test.go | 13 +++++++++++++ 3 files changed, 38 insertions(+) diff --git a/strutil/string.go b/strutil/string.go index 3ea2f65..628ad11 100644 --- a/strutil/string.go +++ b/strutil/string.go @@ -445,3 +445,14 @@ func IndexOffset(str string, substr string, idxFrom int) int { return strings.Index(str[idxFrom:], substr) + idxFrom } + +// ReplaceByMap returns a copy of `origin`, +// which is replaced by a map in unordered way, case-sensitively. +// Play: todo +func ReplaceByMap(str string, replaces map[string]string) string { + for k, v := range replaces { + str = strings.ReplaceAll(str, k, v) + } + + return str +} diff --git a/strutil/string_example_test.go b/strutil/string_example_test.go index 02bf988..dd43755 100644 --- a/strutil/string_example_test.go +++ b/strutil/string_example_test.go @@ -525,3 +525,17 @@ func ExampleIndexOffset() { // -1 // -1 } + +func ExampleReplaceByMap() { + str := "ac ab ab ac" + replaces := map[string]string{ + "a": "1", + "b": "2", + } + + result := ReplaceByMap(str, replaces) + + fmt.Println(result) + // Output: + // 1c 12 12 1c +} diff --git a/strutil/string_test.go b/strutil/string_test.go index 590c844..f80cf61 100644 --- a/strutil/string_test.go +++ b/strutil/string_test.go @@ -397,3 +397,16 @@ func TestIndexOffset(t *testing.T) { assert.Equal(IndexOffset(str, "d", len(str)), -1) assert.Equal(IndexOffset(str, "f", -1), -1) } + +func TestReplaceByMap(t *testing.T) { + assert := internal.NewAssert(t, "TestReplaceByMap") + + str := "ac ab ab ac" + replaces := map[string]string{ + "a": "1", + "b": "2", + } + + assert.Equal(str, "ac ab ab ac") + assert.Equal(ReplaceByMap(str, replaces), "1c 12 12 1c") +}