func main() {
fmt.Println(ReplaceRight("niqinge~很帅~也很棒", "~", "@@", 1))
fmt.Println(ReplaceRight("niqinge~很帅~也很棒", "~", "@@", 2))
}
func ReplaceRight(s, old, new string, n int) string {
if old == new || n == 0 {
return s // avoid allocation
}
// Compute number of replacements.
m := strings.Count(s, old)
if m == 0 {
return s // avoid allocation
} else if n < 0 || m < n {
n = m
}
// Apply replacements to buffer.
var b strings.Builder
b.Grow(len(s) + n*(len(new)-len(old)))
var preIndex int
for i := 0; i < m; i++ {
index := strings.Index(s[preIndex:], old)
if index < 0 {
b.WriteString(s[preIndex:])
break
}
if i < m-n {
b.WriteString(s[preIndex : index+preIndex+len(old)])
preIndex += index + len(old)
continue
}
b.WriteString(s[preIndex : index+preIndex])
b.WriteString(new)
preIndex += index + len(old)
}
b.WriteString(s[preIndex:])
return b.String()
}
输出:
niqinge~很帅@@也很棒
niqinge@@很帅@@也很棒
参考官方方法: func Replace(s, old, new string, n int) string {}
文章来源地址https://www.toymoban.com/news/detail-609053.html
文章来源:https://www.toymoban.com/news/detail-609053.html
到了这里,关于golang语言字符串从右方替换字符串(参考官方strings.Replace)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!