【问题标题】:replace strings n times, starting from the end从末尾开始替换字符串 n 次
【发布时间】:2015-01-14 22:28:04
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: string go


    【解决方案1】:

    没有你想要的标准函数。

    备选方案 #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() 来查找可替换的子字符串并替换它们。

    【讨论】:

      猜你喜欢
      • 2016-02-06
      • 1970-01-01
      • 2014-04-29
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      相关资源
      最近更新 更多