douwen8118 2016-12-29 23:21
浏览 1079
已采纳

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

In PHP we can do something like :

$result = str_replace($str,$array1,$array2);

Where $array1 and $array2 are array of elements, this makes php replace all array1 elements by array2 elements. Is there any equivalent to this using the Golang? I have tried the same php approach but it did not work :

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

I know I can do something like :

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

That would work but I need to use arrays directly because the arrays of replacements will be created dynamically.

  • 写回答

3条回答 默认 最新

  • douguaidian8021 2016-12-30 03:03
    关注

    I believe performance would be much better if you first zip both arrays in a single replacement array and then run just one replacer pass over the target string because strings.Replacer is fairly optimized for various cases and because the replacement algorithm would need to be run only once.

    Something like this would do:

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数
  • ¥15 ADS时域 连续相位观察方法
  • ¥15 Opencv配置出错
  • ¥15 模电中二极管,三极管和电容的应用
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
  • ¥15 气象网格数据与卫星轨道数据如何匹配
  • ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
  • ¥15 微软账户问题不小心注销了好像
  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused