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

我正在从用户获取实际的位置地址,并尝试安排它创建一个URL,以后可以从Google地理编码API获取 JSON响应.

最终的URL字符串结果应该类似于this one,没有空格:

07001

我不知道如何替换我的URL字符串中的空格,而是使用逗号.我读了一些关于字符串和正则表达式的包,我创建了以下代码

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
}
你可以使用 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

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...