Skip to content

Commit

Permalink
feat: add ReplaceStringAtByteIndexBatch string function
Browse files Browse the repository at this point in the history
  • Loading branch information
wubin48435 committed May 30, 2024
1 parent b9aa6c0 commit 7e71c9a
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
16 changes: 16 additions & 0 deletions toolkit/stringutils/stringutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
45 changes: 45 additions & 0 deletions toolkit/stringutils/stringutils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})
}
}

0 comments on commit 7e71c9a

Please sign in to comment.