问题描述

我从用户那里获取了一个物理位置地址,并尝试将其安排为创建一个 URL,该 URL 稍后将用于从 Google Geocode API 获取 JSON 响应.

I am getting a physical location address from a user and trying to arrange it to create a URL that would use later to get a JSON response from Google Geocode API.

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

The final URL string result should be similar to this one, without spaces:

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

I do not know how to replace white spaces in my URL string and have commas instead. I did read a little about the strings and regexp packages and I have created the following code:

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.替换
strings.Replace
package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "a space-separated string"
    str = strings.Replace(str, " ", ",", -1)
    fmt.Println(str)
}
strings.Replacer
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(" ", ",", "	", ",")

func main() {
    str := "a space- and	tab-separated string"
    str = replacer.Replace(str)
    fmt.Println(str)
}
url.QueryEscape
url.QueryEscape

这篇关于如何在 Golang 中替换字符串中的单个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!