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

huangapple go评论78阅读模式
英文:

How to replace a single character inside a string in Golang?

问题

我从用户那里得到一个物理位置地址,并尝试整理它以创建一个URL,稍后可以使用它从Google Geocode API获取JSON响应。

最终的URL字符串结果应该类似于这个,没有空格:

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

我不知道如何替换URL字符串中的空格,并用逗号代替。我稍微阅读了一下strings和regexp包,并创建了以下代码:

package main

import (
	"fmt"
	"bufio"
	"os"
	"http"
)

func main() {
	// 获取物理地址
	r := bufio.NewReader(os.Stdin)	
	fmt.Println("输入一个物理位置地址:")
    line, _, _ := r.ReadLine()
	
	// 打印输入的地址
	address := string(line)
	fmt.Println(address) // 需要看看我得到了什么
	
	// 创建URL并获取该地址的Google Geocode API JSON响应
	URL := "http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=true"
	fmt.Println(URL)
	
	result, _ := http.Get(URL)
	fmt.Println(result) // 看看我在这一点上得到了什么
}
英文:

I am getting a physical location address from a user and trying to arrange it to create a URL that would use later to get a JSON response from Google Geocode API.

The final URL string result should be similar to this one, without spaces:

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

I do not know how to replace white spaces in my URL string and have commas instead. I did read a little about the strings and regexp packages and I have created the following code:

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
}

</pre></code>

答案1

得分: 97

你可以使用strings.Replace

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "一个以空格分隔的字符串"
    str = strings.Replace(str, " ", ",", -1)
    fmt.Println(str)
}

如果你需要替换多个内容,或者需要多次进行相同的替换,最好使用strings.Replacer

package main

import (
    "fmt"
    "strings"
)

// replacer将空格替换为逗号,制表符替换为逗号。
// 它是一个包级变量,所以我们可以轻松地重用它,但是
// 这个程序没有利用这个特性。
var replacer = strings.NewReplacer(" ", ",", "\t", ",")

func main() {
    str := "一个以空格和制表符分隔的字符串"
    str = replacer.Replace(str)
    fmt.Println(str)
}

当然,如果你是为了编码的目的而进行替换,比如URL编码,那么最好使用专门用于此目的的函数,比如url.QueryEscape

英文:

You can use strings.Replace.

package main

import (
    &quot;fmt&quot;
    &quot;strings&quot;
)

func main() {
    str := &quot;a space-separated string&quot;
    str = strings.Replace(str, &quot; &quot;, &quot;,&quot;, -1)
    fmt.Println(str)
}

If you need to replace more than one thing, or you'll need to do the same replacement over and over, it might be better to use a strings.Replacer:

package main

import (
    &quot;fmt&quot;
    &quot;strings&quot;
)

// replacer replaces spaces with commas and tabs with commas.
// It&#39;s a package-level variable so we can easily reuse it, but
// this program doesn&#39;t take advantage of that fact.
var replacer = strings.NewReplacer(&quot; &quot;, &quot;,&quot;, &quot;\t&quot;, &quot;,&quot;)

func main() {
    str := &quot;a space- and\ttab-separated string&quot;
    str = replacer.Replace(str)
    fmt.Println(str)
}

And of course if you're replacing for the purpose of encoding, such as URL encoding, then it might be better to use a function specifically for that purpose, such as url.QueryEscape

答案2

得分: 10

如果您需要替换字符串中的所有字符出现,则使用strings.ReplaceAll

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "一个以空格分隔的字符串"
    str = strings.ReplaceAll(str, " ", ",")
    fmt.Println(str)
}
英文:

If you need to replace all occurrences of the character in the string, then use strings.ReplaceAll:

package main

import (
    &quot;fmt&quot;
    &quot;strings&quot;
)

func main() {
    str := &quot;a space-separated string&quot;
    str = strings.ReplaceAll(str, &quot; &quot;, &quot;,&quot;)
    fmt.Println(str)
}

huangapple
  • 本文由 发表于 2011年11月19日 07:45:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/8190540.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定