gpt4 book ai didi

go - 如何从 Go 中的字符串中替换最后两个 '/' 字符

转载 作者:数据小太阳 更新时间:2023-10-29 03:38:41 24 4
gpt4 key购买 nike

profilePicture := strings.Replace(tempProfile, "/", "%2F", -2)

我试过这段代码,但它替换了字符串中的所有 /

tempProfile = "https://firebasestorage.googleapis.com/v0/b/passporte-b9070.appspot.com/o/profilePicturesOfAbmin/original/1492674641download (3).jpg?alt=media"

想要的结果是

tempProfile = "https://firebasestorage.googleapis.com/v0/b/passporte-b9070.appspot.com/o/profilePicturesOfAbmin%2Foriginal%2F1492674641download (3).jpg?alt=media"

最佳答案

首先,来自documentation :

Replace returns a copy of the string s with the first n non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string. If n < 0, there is no limit on the number of replacements. (Emphasis added)

这解释了为什么您的 -2 不工作。

解决您所述问题的最简单方法可能是这样的:

parts := strings.Split(tempProfile, "/")
parts = append(parts[:len(parts)-3], strings.Join(parts[len(parts)-3:], "%2F"))
profilePicture := strings.Join(parts, "/")

但更好的方法可能是使用 url 进行适当的 URL 编码包。

关于go - 如何从 Go 中的字符串中替换最后两个 '/' 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43513474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com