doucheng8471 2011-11-18 23:45
浏览 951
已采纳

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

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.

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

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

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
}

  • 写回答

1条回答 默认 最新

  • duansan9435 2011-11-19 00:53
    关注

    You can use strings.Replace.

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

    If you need to replace more than one thing, or you'll need to do the same replacement over and over, it might be better to use a 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)
    }
    

    And of course if you're replacing for the purpose of encoding, such as URL encoding, then it might be better to use a function specifically for that purpose, such as url.QueryEscape

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作