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

标签 string replace char go

我从用户那里获取了一个物理位置地址,并尝试将其安排为创建一个 URL,该 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 字符串中的空格并使用逗号代替。我确实阅读了一些关于字符串和正则表达式包的信息,并创建了以下代码:

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)
}

如果您需要更换不止一件东西,或者您需要一遍又一遍地进行相同的更换,最好使用 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

关于string - 如何在 Golang 中替换字符串中的单个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8190540/

相关文章:

Python 字符串比较

.net - 在不使用Regex的情况下,.Net中是否存在不区分大小写的字符串替换?

C - 找到一个单词并获取接下来的两个单词

python - python中str和bytes有什么关系?

c# - 如何在日志中隐藏密码

regex - 使用正则表达式的条件子表达式替换

swift - 我的代码在 textViewDidChangeSelection 中插入两个字符而不是一个

c - "different width due to prototype"警告是什么意思?

c# - 将单词转换为字符数组

postgresql删除字符开头