2011-11-18 173 views
14

我正在从用户那里获取一个物理位置地址,并试图安排它创建一个URL,以便以后使用它来获取来自Google Geocode API的JSON响应。如何替换Golang中的字符串中的单个字符?

最终URL字符串的结果应该是类似this one,无空格:

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

我不知道如何来代替我的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 
} 

+2

字符串是go中的不可变对象。所以你不能替换字符串中的字符。相反,你可以用替换的say片创建一个新的字符串。 – user510306

回答

40

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

+0

谢谢你的回答,如果我可以问 - 我想用多个不同的值替换多个字符。例如>用B代替A,用D代替C(这只是例子)。我使用多个'string.Replace(...)'语句,它工作正常,但寻找更好的选择,如果有的话? – Pranav

+0

我已经更新了我的回答,提到了'strings.Replacer',当我最初回答这个问题时,这并不存在。 –

+1

再一次,非常感谢你的努力和时间。你教了我一个课,睁开眼睛阅读是真正的阅读:) 昨天,我错过了这个'replacer'阅读文档。谢谢。 – Pranav