Speed up and simplify string.replace

pull/937/head
Nick Treleaven 2019-06-29 16:29:29 +01:00 committed by Alexander Medvednikov
parent 53e439bc99
commit 75da1e4240
1 changed files with 9 additions and 18 deletions

View File

@ -77,28 +77,19 @@ pub fn (s string) replace(rep, with string) string {
if s.len == 0 || rep.len == 0 { if s.len == 0 || rep.len == 0 {
return s return s
} }
if !s.contains(rep) {
return s
}
// println('"$s" replace "$rep" with "$with" rep.len=$rep.len') // println('"$s" replace "$rep" with "$with" rep.len=$rep.len')
// TODO PERF Allocating ints is expensive. Should be a stack array // TODO PERF Allocating ints is expensive. Should be a stack array
// Get locations of all reps within this string // Get locations of all reps within this string
mut idxs := []int{} mut idxs := []int{}
// idxs := []int { mut rem := s
// 2, 8, 14 mut rstart := 0
// } for {
for i := 0; i < s.len; i++ { mut i := rem.index(rep)
// Do we have the string we are looking for (rep) starting at i? if i < 0 {break}
// Go thru all chars in rep and compare. idxs << rstart + i
mut rep_i := 0 i += rep.len
mut j := i rstart += i
for rep_i < rep.len && j < s.len && s[j] == rep[rep_i] { rem = rem.substr(i, rem.len)
rep_i++
j++
}
if rep_i == rep.len {
idxs << i
}
} }
// Dont change the string if there's nothing to replace // Dont change the string if there's nothing to replace
if idxs.len == 0 { if idxs.len == 0 {