如何在Go语言中替换字符串中的最后两个’/’字符

huangapple go评论80阅读模式
英文:

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, &quot;/&quot;)
parts = append(parts[:len(parts)-3], strings.Join(parts[len(parts)-3:], &quot;%2F&quot;))
profilePicture := strings.Join(parts, &quot;/&quot;)

But a better approach is probably to do proper URL encoding with the url package.

huangapple
  • 本文由 发表于 2017年4月20日 15:55:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/43513474.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定