String 如何在Golang中替换字符串中的单个字符?
我从一个用户那里获得了一个物理位置地址,并试图将其安排为创建一个URL,稍后将使用该URL从Google Geocode API获取JSON响应 最终URL字符串结果应类似于,不带空格: 我不知道如何替换URL字符串中的空格,而是使用逗号。我确实读了一些关于字符串和regexp包的内容,并创建了以下代码:String 如何在Golang中替换字符串中的单个字符?,string,replace,char,go,String,Replace,Char,Go,我从一个用户那里获得了一个物理位置地址,并试图将其安排为创建一个URL,稍后将使用该URL从Google Geocode API获取JSON响应 最终URL字符串结果应类似于,不带空格: 我不知道如何替换URL字符串中的空格,而是使用逗号。我确实读了一些关于字符串和regexp包的内容,并创建了以下代码: package main import ( "fmt" "bufio" "os" "http" ) func main() { // Get th
package main
import (
"fmt"
"bufio"
"os"
"http"
)
func main() {
// Get the physical address
r := bufio.NewReader(os.Stdin)
fmt.Println("Enter a physical location address: ")
line, _, _ := r.ReadLine()
// Print the inputted address
address := string(line)
fmt.Println(address) // Need to see what I'm getting
// Create the URL and get Google's Geocode API JSON response for that address
URL := "http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=true"
fmt.Println(URL)
result, _ := http.Get(URL)
fmt.Println(result) // To see what I'm getting at this point
}
您可以使用
如果您需要更换多件物品,或者需要反复进行相同的更换,那么最好使用:
当然,如果为了编码目的而替换,例如URL编码,那么最好使用专门用于该目的的函数,例如如果需要替换字符串中所有出现的字符,则使用:
字符串是go中不可变的对象。所以不能替换字符串中的字符。相反,您可以使用say slices和replacement创建一个新字符串。谢谢您的回答,如果我可以问的话-我想用多个不同的值替换多个字符。e、 g>用B替换A,用D替换C(这只是一个例子)。我使用了多个
string.Replace(…)
语句,虽然效果很好,但如果有更好的替代方案,我会寻找吗?我已经更新了我的答案,提到了strings.Replacer,这在我最初回答这个问题时是不存在的。再次感谢您的努力和时间。你给了我一个教训,那就是睁大眼睛阅读才是真正的阅读:)我昨天在看文档时错过了这个replacer
。谢谢
package main
import (
"fmt"
"strings"
)
func main() {
str := "a space-separated string"
str = strings.Replace(str, " ", ",", -1)
fmt.Println(str)
}
package main
import (
"fmt"
"strings"
)
// replacer replaces spaces with commas and tabs with commas.
// It's a package-level variable so we can easily reuse it, but
// this program doesn't take advantage of that fact.
var replacer = strings.NewReplacer(" ", ",", "\t", ",")
func main() {
str := "a space- and\ttab-separated string"
str = replacer.Replace(str)
fmt.Println(str)
}
package main
import (
"fmt"
"strings"
)
func main() {
str := "a space-separated string"
str = strings.ReplaceAll(str, " ", ",")
fmt.Println(str)
}