1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

string: fix replace_each() (#9415)

This commit is contained in:
yuyi 2021-03-22 16:46:45 +08:00 committed by GitHub
parent 400b4027c9
commit 320cd00203
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 1 deletions

View File

@ -329,15 +329,22 @@ pub fn (s string) replace_each(vals []string) string {
mut new_len := s.len
mut idxs := []RepIndex{}
mut idx := 0
s_ := s.clone()
for rep_i := 0; rep_i < vals.len; rep_i += 2 {
// vals: ['rep1, 'with1', 'rep2', 'with2']
rep := vals[rep_i]
with := vals[rep_i + 1]
for {
idx = s.index_after(rep, idx)
idx = s_.index_after(rep, idx)
if idx == -1 {
break
}
// The string already found is set to `/del`, to avoid duplicate searches.
for i in 0 .. rep.len {
unsafe {
s_.str[idx + i] = 127
}
}
// We need to remember both the position in the string,
// and which rep/with pair it refers to.
idxs << RepIndex{

View File

@ -329,6 +329,8 @@ fn test_replace_each() {
'b',
])
assert y == 'bbbb'
s2 := 'hello_world hello'
assert s2.replace_each(['hello_world', 'aaa', 'hello', 'bbb']) == 'aaa bbb'
}
fn test_itoa() {