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

时间:2011-11-18 23:45:08

标签: string replace char go

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

最终的URL字符串结果应与this one类似,不含空格:

  

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
}

2 个答案:

答案 0 :(得分:67)

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

答案 1 :(得分:4)

如果您需要替换字符串中所有出现的字符,请使用strings.ReplaceAll

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "a space-separated string"
    str = strings.ReplaceAll(str, " ", ",")
    fmt.Println(str)
}
相关问题