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

lin*_*nqu 5 string go

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

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

func Replace(s, old, new string, n int) string
Run Code Online (Sandbox Code Playgroud)

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

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

icz*_*cza 4

没有您需要的标准功能。

替代方案#1:使用反向

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

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)
}
Run Code Online (Sandbox Code Playgroud)

您的解决方案是:

Rev(strings.Replace(Rev(s), Rev(old), Rev(new), n))
Run Code Online (Sandbox Code Playgroud)

替代方案#2:自己动手

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