这是我使用 golang 的第二天,我可能会问一个非常基本的问题:
我想替换字符串的一部分,这就是 strings.Replace适用于:
func Replace(s, old, new string, n int) string
最后一个参数是 old
被 new
替换的次数 - 从字符串的开头开始。
是否有类似的从尾部开始的标准函数?
最佳答案
没有您要的标准功能。
备选方案#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:自己动手
您可以简单地使用for
和strings.LastIndex()
找到可替换的子串并替换它们。
关于string - 替换字符串 n 次,从末尾开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27942769/