替换字符串 n 次,从末尾开始

replace strings n times, starting from the end

这是我使用 golang 的第二天,我可能会问一个非常基本的问题:

我想替换字符串的一部分,这就是 strings.Replace 的优点:

func Replace(s, old, new string, n int) string

最后一个参数是 oldnew 替换的次数 - 从字符串的开头开始。

有没有类似的从尾开始的标准函数?

没有您要的标准功能

备选方案 #1:反向

使用字符串反转函数(取自here):

func Rev(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

您的解决方案是:

Rev(strings.Replace(Rev(s), Rev(old), Rev(new), n))

备选方案 #2:自己动手

您可以简单地使用 forstrings.LastIndex() 来查找可替换的子字符串并替换它们。