From 7e71c9a8616cd9868adea277b334a82521b59f5e Mon Sep 17 00:00:00 2001 From: wubin48435 Date: Thu, 30 May 2024 12:25:11 +0800 Subject: [PATCH] feat: add ReplaceStringAtByteIndexBatch string function --- toolkit/stringutils/stringutils.go | 16 +++++++++ toolkit/stringutils/stringutils_test.go | 45 +++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/toolkit/stringutils/stringutils.go b/toolkit/stringutils/stringutils.go index 420d8ece..028da28b 100644 --- a/toolkit/stringutils/stringutils.go +++ b/toolkit/stringutils/stringutils.go @@ -65,3 +65,19 @@ func ReplaceStringAtByteIndex(in string, replace string, start int, end int) str result = append(result, out[end:]...) return string(result) } + +func ReplaceStringAtByteIndexBatch(in string, args []string, locs [][]int) string { + out := []byte(in) + result := make([]byte, 0) + end := 0 + for i, loc := range locs { + arg := args[i] + r := []byte(arg) + start := loc[0] + result = append(result, out[end:start]...) + result = append(result, r...) + end = loc[1] + } + result = append(result, out[end:]...) + return string(result) +} diff --git a/toolkit/stringutils/stringutils_test.go b/toolkit/stringutils/stringutils_test.go index e5824ef1..ed4e4296 100644 --- a/toolkit/stringutils/stringutils_test.go +++ b/toolkit/stringutils/stringutils_test.go @@ -271,3 +271,48 @@ func TestReplaceStringAtIndex(t *testing.T) { }) } } + +func TestReplaceStringAtByteIndexBatch(t *testing.T) { + in := `INSERT INTO user ("name", "age") VALUES (?, ?);` + loc := IndexAll(in, "?", -1) + + in2 := `我爱北京天安门,啦啦啦` + loc2 := IndexAll(in2, "天安门", -1) + + type args struct { + in string + args []string + locs [][]int + } + tests := []struct { + name string + args args + want string + }{ + { + name: "", + args: args{ + in: in, + args: []string{"'wubin'", "18"}, + locs: loc, + }, + want: `INSERT INTO user ("name", "age") VALUES ('wubin', 18);`, + }, + { + name: "", + args: args{ + in: in2, + args: []string{"颐和园"}, + locs: loc2, + }, + want: `我爱北京颐和园,啦啦啦`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := ReplaceStringAtByteIndexBatch(tt.args.in, tt.args.args, tt.args.locs); got != tt.want { + t.Errorf("ReplaceStringAtByteIndexBatch() = %v, want %v", got, tt.want) + } + }) + } +}