2011-11-18 374 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