aboutsummaryrefslogtreecommitdiff
path: root/src/bytes/bytes.go
diff options
context:
space:
mode:
Diffstat (limited to 'src/bytes/bytes.go')
-rw-r--r--src/bytes/bytes.go25
1 files changed, 14 insertions, 11 deletions
diff --git a/src/bytes/bytes.go b/src/bytes/bytes.go
index 4bc375df19..8198415c3e 100644
--- a/src/bytes/bytes.go
+++ b/src/bytes/bytes.go
@@ -1192,19 +1192,22 @@ func Replace(s, old, new []byte, n int) []byte {
t := make([]byte, len(s)+n*(len(new)-len(old)))
w := 0
start := 0
- for i := 0; i < n; i++ {
- j := start
- if len(old) == 0 {
- if i > 0 {
- _, wid := utf8.DecodeRune(s[start:])
- j += wid
- }
- } else {
- j += Index(s[start:], old)
+ if len(old) > 0 {
+ for range n {
+ j := start + Index(s[start:], old)
+ w += copy(t[w:], s[start:j])
+ w += copy(t[w:], new)
+ start = j + len(old)
}
- w += copy(t[w:], s[start:j])
+ } else { // len(old) == 0
w += copy(t[w:], new)
- start = j + len(old)
+ for range n - 1 {
+ _, wid := utf8.DecodeRune(s[start:])
+ j := start + wid
+ w += copy(t[w:], s[start:j])
+ w += copy(t[w:], new)
+ start = j
+ }
}
w += copy(t[w:], s[start:])
return t[0:w]