mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add ReplaceByMap
This commit is contained in:
@@ -445,3 +445,14 @@ func IndexOffset(str string, substr string, idxFrom int) int {
|
|||||||
|
|
||||||
return strings.Index(str[idxFrom:], substr) + idxFrom
|
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
|
||||||
|
}
|
||||||
|
|||||||
@@ -525,3 +525,17 @@ func ExampleIndexOffset() {
|
|||||||
// -1
|
// -1
|
||||||
// -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
|
||||||
|
}
|
||||||
|
|||||||
@@ -397,3 +397,16 @@ func TestIndexOffset(t *testing.T) {
|
|||||||
assert.Equal(IndexOffset(str, "d", len(str)), -1)
|
assert.Equal(IndexOffset(str, "d", len(str)), -1)
|
||||||
assert.Equal(IndexOffset(str, "f", -1), -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")
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user