Speed up and simplify string.replace
parent
53e439bc99
commit
75da1e4240
|
@ -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 {
|
||||||
|
|
Loading…
Reference in New Issue