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 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序