Php Golang将数组元素替换为字符串中的数组元素
在PHP中,我们可以执行以下操作:Php Golang将数组元素替换为字符串中的数组元素,php,arrays,string,go,replace,Php,Arrays,String,Go,Replace,在PHP中,我们可以执行以下操作: $result = str_replace($str,$array1,$array2); str := "hello world" array1 := []string {"hello","world"} array2 := []string {"foo","bar"} r := strings.NewReplacer("hello","foo","world","bar") str = r.Replace(str) 其中$array1和$array2
$result = str_replace($str,$array1,$array2);
str := "hello world"
array1 := []string {"hello","world"}
array2 := []string {"foo","bar"}
r := strings.NewReplacer("hello","foo","world","bar")
str = r.Replace(str)
其中$array1和$array2是元素数组,这使得php用array2元素替换所有array1元素。
使用Golang是否有与此等效的工具?我尝试过相同的php方法,但不起作用:
str := "hello world"
array1 := []string {"hello","world"}
array2 := []string {"foo","bar"}
r := strings.NewReplacer(array1,array2)
str = r.Replace(str)
我知道我可以做一些事情,比如:
$result = str_replace($str,$array1,$array2);
str := "hello world"
array1 := []string {"hello","world"}
array2 := []string {"foo","bar"}
r := strings.NewReplacer("hello","foo","world","bar")
str = r.Replace(str)
这会起作用,但我需要直接使用数组,因为替换数组将动态创建。我找到的解决方案如下:
str := "hello world"
array1 := []string {"hello","world"}
array2 := []string {"foo","bar"}
for i,toreplace := range array1{
r := strings.NewReplacer(toreplace,array2[i])
str = r.Replace(str)
}
fmt.Println(str)
可以创建一个函数
func str_replace(str string, original []string, replacement []string) string {
for i,toreplace := range original{
r := strings.NewReplacer(toreplace,replacement[i])
str = r.Replace(str)
}
return str
}
用法:
str := "hello world"
array1 := []string {"hello","world"}
array2 := []string {"foo","bar"}
str = str_replace(str,array1,array2)
fmt.Println(str)
任何更优雅的解决方案都是非常受欢迎的。我相信,如果您首先将两个数组压缩到一个替换数组中,然后只运行一个替换器来传递目标字符串,性能会更好,因为字符串。替换器针对各种情况进行了相当优化,并且只需要运行替换算法一次 这样做可以:
func zip(a1, a2 []string) []string {
r := make([]string, 2*len(a1))
for i, e := range a1 {
r[i*2] = e
r[i*2+1] = a2[i]
}
return r
}
func main() {
str := "hello world"
array1 := []string{"hello", "world"}
array2 := []string{"foo", "bar"}
str = strings.NewReplacer(zip(array1, array2)...).Replace(str)
fmt.Println(str)
}
地图怎么样
str := "Lorem Ipsum is simply dummy. Lorem Ipsum is text of the printing. Lorem Ipsum is typesetting industry.";
replace := map[string]string{
"Lorem": "LoremReplaced",
"Ipsum": "IpsumReplaced",
"printing": "printingReplaced",
}
for s, r := range replace {
str = strings.Replace(str, s, r, -1)
}
谢谢Pablo,这是一个很好的解决方案,我已经在这两个解决方案上做了一个基准测试,你的解决方案更快、更一致。