为什么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

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

You always apply the replace operation on the original string strValue, so after the loop only the last removable word will be removed (which is not even contained in your example). You should store the result of strings.Replace() (you do that), and use this in the next iteration:

removalString := strValue
for _, wordToRemove := range stringRemove {
    removalString = strings.Replace(removalString, wordToRemove, "", -1)
}

And also use this in your last replacement:

result := strings.Replace(removalString, " ", "", -1)
result1 := strings.ToLower(result)

Then output will be (try it on the Go Playground):

This is  string
thisisstring

Also note that to remove spaces, you can add that to the list of removable words, and you don't need to always create new variables, you can reuse existing ones.

This will also perform the same transformation:

s := "This is a string"
words := []string{"a", "an", " "}

for _, word := range words {
    s = strings.Replace(s, word, "", -1)
}

s = strings.ToLower(s)
fmt.Println(s)

Try it on the Go Playground.

removalString will be set new value each loop. So fmt.Println(removalString) will show the result of last loop.

var removalString string
for _, wordToRemove := range stringRemove {
    removalString = strings.Replace(strValue, wordToRemove, "", -1)
}
fmt.Println(removalString)

You may do like this

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