小编典典

如何在Golang中替换字符串中的单个字符?

go

我正在从用户那里获得一个物理位置地址,并试图安排它来创建一个URL,该URL以后将用于从Google Geocode API获取JSON响应。

最终的URL字符串结果应与类似,但不能有空格:

http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true

我不知道如何替换URL字符串中的空格,而用逗号代替。我确实阅读了一些有关字符串和regexp软件包的信息,并创建了以下代码:

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
}

阅读 422

收藏
2020-07-02

共1个答案

小编典典

您可以使用strings.Replace

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "a space-separated string"
    str = strings.Replace(str, " ", ",", -1)
    fmt.Println(str)
}

如果您需要替换多个内容,或者需要一遍又一遍地进行相同的替换,则最好使用strings.Replacer

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)
}

当然,如果要出于编码目的(例如URL编码)进行替换,则最好使用专门用于该目的的函数,例如url.QueryEscape

2020-07-02