1 Star 0 Fork 0

mosache/go-zero

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
replacer.go 1.01 KB
一键复制 编辑 原始数据 按行查看 历史
kevwan 提交于 2020-08-19 16:00 . fix golint warnings
package stringx
import "strings"
type (
Replacer interface {
Replace(text string) string
}
replacer struct {
node
mapping map[string]string
}
)
func NewReplacer(mapping map[string]string) Replacer {
var rep = &replacer{
mapping: mapping,
}
for k := range mapping {
rep.add(k)
}
return rep
}
func (r *replacer) Replace(text string) string {
var builder strings.Builder
var chars = []rune(text)
var size = len(chars)
var start = -1
for i := 0; i < size; i++ {
child, ok := r.children[chars[i]]
if !ok {
builder.WriteRune(chars[i])
continue
}
if start < 0 {
start = i
}
var end = -1
if child.end {
end = i + 1
}
var j = i + 1
for ; j < size; j++ {
grandchild, ok := child.children[chars[j]]
if !ok {
break
}
child = grandchild
if child.end {
end = j + 1
i = j
}
}
if end > 0 {
i = j - 1
builder.WriteString(r.mapping[string(chars[start:end])])
} else {
builder.WriteRune(chars[i])
}
start = -1
}
return builder.String()
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/mosache/go-zero.git
git@gitee.com:mosache/go-zero.git
mosache
go-zero
go-zero
dfb45c801a6c

搜索帮助