英文:
How to replace the last two '/' characters from a string in Go
问题
profilePicture := strings.Replace(tempProfile, "/", "%2F", -1)
我尝试了这段代码,但它替换了字符串中的所有 /
。
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"
英文:
profilePicture := strings.Replace(tempProfile, "/", "%2F", -2)
I tried this code but its replace all /
in the string
tempProfile = "https://firebasestorage.googleapis.com/v0/b/passporte-b9070.appspot.com/o/profilePicturesOfAbmin/original/1492674641download (3).jpg?alt=media"
the result which want is
tempProfile = "https://firebasestorage.googleapis.com/v0/b/passporte-b9070.appspot.com/o/profilePicturesOfAbmin%2Foriginal%2F1492674641download (3).jpg?alt=media"
答案1
得分: 4
首先,根据文档:
> Replace函数返回将字符串s中的前n个非重叠的old实例替换为new后的副本。如果old为空,则它在字符串开头和每个UTF-8序列之后进行匹配,对于一个包含k个rune的字符串,最多会产生k+1个替换。如果n < 0,则替换的数量没有限制。(强调部分)
这解释了为什么你的-2不起作用。
解决你所述问题的最简单方法可能是这样的:
parts := strings.Split(tempProfile, "/")
parts = append(parts[:len(parts)-3], strings.Join(parts[len(parts)-3:], "%2F"))
profilePicture := strings.Join(parts, "/")
但更好的方法可能是使用url
包进行正确的URL编码。
英文:
First, from the 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)
Which explains why your -2 isn't working.
The simplest approach to your stated problem is probably something like this:
parts := strings.Split(tempProfile, "/")
parts = append(parts[:len(parts)-3], strings.Join(parts[len(parts)-3:], "%2F"))
profilePicture := strings.Join(parts, "/")
But a better approach is probably to do proper URL encoding with the url
package.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论