Golang 用字符串中的数组元素替换数组元素

Fao*_*ech 2 php arrays string replace go

在 PHP 中,我们可以执行以下操作:

$result = str_replace($str,$array1,$array2);
Run Code Online (Sandbox Code Playgroud)

$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)
Run Code Online (Sandbox Code Playgroud)

我知道我可以做类似的事情:

str := "hello world"
array1 :=  []string {"hello","world"}
array2 :=  []string {"foo","bar"}
r := strings.NewReplacer("hello","foo","world","bar")
str = r.Replace(str)
Run Code Online (Sandbox Code Playgroud)

这会起作用,但我需要直接使用数组,因为将动态创建替换数组。

Pab*_*oni 6

我相信如果您首先将两个数组压缩到一个替换数组中,然后只在目标字符串上运行一个替换器,那么性能会好得多,因为 strings.Replacer 针对各种情况进行了相当优化,并且只需要运行替换算法一次。

像这样的事情会做:

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)
}
Run Code Online (Sandbox Code Playgroud)