微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在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

原文地址:https://www.jb51.cc/go/186978.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐