【问题标题】:Golang replace array elements by array elements in stringGolang用字符串中的数组元素替换数组元素
【发布时间】:2017-05-14 07:15:45
【问题描述】:

在 PHP 中我们可以这样做:

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

其中 $array1 和 $array2 是元素数组,这使得 php 将所有 array1 元素替换为 array2 元素。 使用 Golang 有什么等价的吗?我尝试了相同的 php 方法,但它不起作用:

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

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

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

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

【问题讨论】:

    标签: php arrays string go replace


    【解决方案1】:

    我找到的解决方案如下:

    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)
    

    任何更优雅的解决方案都非常受欢迎。

    【讨论】:

      【解决方案2】:

      我相信,如果您首先将两个数组压缩到一个替换数组中,然后只对目标字符串运行一个替换器传递,那么性能会更好,因为 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)
      }
      

      【讨论】:

      • 谢谢Pablo,这是一个很好的解决方案,我对这两个解决方案做了一个基准测试,你的更快更一致。
      【解决方案3】:

      地图怎么样?

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

      【讨论】:

        猜你喜欢
        • 2014-05-07
        • 2022-06-17
        • 2019-11-15
        • 1970-01-01
        • 2020-09-21
        • 2011-04-13
        • 1970-01-01
        • 1970-01-01
        • 2011-04-07
        相关资源
        最近更新 更多