dthp96899 2018-11-26 09:47
浏览 654

为什么string.Replace在Golang中不起作用

I'm making a program to remove the letters from a string if they exsists. But the expected result will not come. The Program I have tried is below:-

package main

import (
  "fmt"
  "strings"
)

func main() {
  strValue := "This is a string"
  stringRemove := []string{"a", "an"}
  var removalString string
  for _, wordToRemove := range stringRemove {
      removalString = strings.Replace(strValue, wordToRemove, "", -1)
  }
  fmt.Println(removalString)
  result := strings.Replace(strValue, " ", "", -1)
  result1 := strings.ToLower(result)
  fmt.Println(result1)
}

Output:-

This is a string
thisisastring

If I use the line fmt.Println(removalString) in the for loop then it will print the result:-

output:-

This is  string
This is a string
This is a string
thisisastring

Expected output:-

thisisstring

kheedn li link

  • 写回答

3条回答 默认 最新

  • duanche4578 2018-11-26 09:53
    关注

    this is what youre looking for:

    package main
    
    import (
      "fmt"
      "strings"
    )
    
    func main() {
      strValue := "This is a string"
      stringRemove := []string{"a", "an"}
      removalString := strValue
      for _, wordToRemove := range stringRemove {
          removalString = strings.Replace(removalString, wordToRemove, "", -1)
      }
      fmt.Println(removalString)
      result := strings.Replace(strValue, " ", "", -1)
      result1 := strings.ToLower(result)
      fmt.Println(result1)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么