You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.0 KiB
Go
58 lines
1.0 KiB
Go
package stringx
|
|
|
|
import "strings"
|
|
|
|
type (
|
|
// Replacer interface wraps the Replace method.
|
|
Replacer interface {
|
|
Replace(text string) string
|
|
}
|
|
|
|
replacer struct {
|
|
*node
|
|
mapping map[string]string
|
|
}
|
|
)
|
|
|
|
// NewReplacer returns a Replacer.
|
|
func NewReplacer(mapping map[string]string) Replacer {
|
|
rep := &replacer{
|
|
node: new(node),
|
|
mapping: mapping,
|
|
}
|
|
for k := range mapping {
|
|
rep.add(k)
|
|
}
|
|
rep.build()
|
|
|
|
return rep
|
|
}
|
|
|
|
// Replace replaces text with given substitutes.
|
|
func (r *replacer) Replace(text string) string {
|
|
var buf strings.Builder
|
|
target := []rune(text)
|
|
cur := r.node
|
|
nextStart := 0
|
|
for len(target) != 0 {
|
|
used, jump, matched := cur.longestMatch(target, nextStart)
|
|
if matched {
|
|
replaced := r.mapping[string(target[:used])]
|
|
target = append([]rune(replaced), target[used:]...)
|
|
cur = r.node
|
|
nextStart = 0
|
|
} else {
|
|
buf.WriteString(string(target[:used]))
|
|
target = target[used:]
|
|
if jump != nil {
|
|
cur = jump
|
|
nextStart = jump.depth
|
|
} else {
|
|
cur = r.node
|
|
nextStart = 0
|
|
}
|
|
}
|
|
}
|
|
return buf.String()
|
|
}
|