moa*_*alf 28 string replace char go
我从用户那里获得了一个物理位置地址,并尝试安排它来创建一个URL,以便稍后从Google Geocode API获取JSON响应.
最终的URL字符串结果应与此类似,不带空格:
我不知道如何替换我的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
}
Run Code Online (Sandbox Code Playgroud)
Eva*_*haw 76
你可以用strings.Replace.
package main
import (
"fmt"
"strings"
)
func main() {
str := "a space-separated string"
str = strings.Replace(str, " ", ",", -1)
fmt.Println(str)
}
Run Code Online (Sandbox Code Playgroud)
如果您需要更换多件物品,或者您需要反复进行相同的更换,最好使用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)
}
Run Code Online (Sandbox Code Playgroud)
当然,如果您为了编码的目的而替换,例如URL编码,那么最好使用专门用于此目的的函数,例如 url.QueryEscape
如果需要替换字符串中所有出现的字符,请使用strings.ReplaceAll:
package main
import (
"fmt"
"strings"
)
func main() {
str := "a space-separated string"
str = strings.ReplaceAll(str, " ", ",")
fmt.Println(str)
}
Run Code Online (Sandbox Code Playgroud)