当前位置: 首页 > 面试题库 >

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

秋和雅
2023-03-14
问题内容

我正在从用户那里获得一个物理位置地址,并试图安排它来创建一个URL,该URL以后将用于从Google Geocode API获取JSON响应。

最终的URL字符串结果应与此类似,但不能有空格:

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

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

问题答案:

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



 类似资料:
  • 问题内容: 如何替换字符串(字符串以上)中的所有字符,应该看起来像? 问题答案: 一种无需正则表达式的简单方法: https://play.golang.org/p/B3c9Ket9fp 您最初可能会想些什么: https://play.golang.org/p/nbNNFJApPp

  • 问题内容: 问题是需要替换给定字符串中的单个字符,同时保留字符串中的其他字符。 代码是: 问题答案: 您几乎做到了,只需在循环中添加一个计数器即可:

  • 我希望我的程序替换输入字符串中的每个元音。

  • 问题内容: 我正在使用一个喜欢: 我使用的是哪里。这行代码对我不起作用。我想知道自己在做什么错? 问题答案: 尽管看起来可能存在一些语法问题,但是代码看起来或多或少还可以。这是一个工作示例:

  • 我有一个PHP脚本这是一个字符串替换函数,它接受数组中的字符,如果在字符串中找到任何字符,就替换它们。是否有与该函数等价的java函数。我找到了一些方法,但有些是使用循环,有些是重复语句,但在Java中没有找到类似的单行解决方案。

  • 问题内容: 在python中,字符串可变吗?该行引发错误 TypeError:’str’对象不支持项目分配 我可以看到原因(因为我可以编写someString [3] =“ test”,这显然是非法的),但是在python中有没有这样做的方法? 问题答案: Python字符串是不可变的,这意味着它们不支持项目或切片分配。您将必须使用ie或其他合适的方法来构建新的字符串。