如何在Golang中的字符串中替换单个字符?
发布时间:2020-12-16 19:20:24 所属栏目:大数据 来源:网络整理
导读:我正在从用户处获取实际的位置地址,并尝试安排它创建一个URL,以后可以从Google地理编码API获取 JSON响应. 最终的URL字符串结果应该类似于this one,没有空格: 07001 我不知道如何替换我的URL字符串中的空格,而是使用逗号.我读了一些关于字符串和正则表达式的
我正在从用户处获取实际的位置地址,并尝试安排它创建一个URL,以后可以从Google地理编码API获取
JSON响应.
最终的URL字符串结果应该类似于this one,没有空格:
我不知道如何替换我的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) } 如果您需要更换多个东西,或者您需要一遍又一遍地进行相同的更换,最好使用 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- andttab-separated string" str = replacer.Replace(str) fmt.Println(str) } 当然,如果要替换编码的目的,例如URL编码,那么可能最好使用专门为此目的的功能,例如 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |