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条)

报告相同问题?

悬赏问题

  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件