I get the output:
Hello World
Hello
With the following code:
package main
import(
"fmt"
"strings"
)
func main(){
s := "Hello World"
fmt.Println(strings.NewReplacer("Hello","").Replace(s))
fmt.Println(strings.NewReplacer("World","").Replace(s))
}
Is this a bug? Is there a better way to remove substrings?
I'm no go expert, but it looks like a bug to me.
This works:
package main
import(
"fmt"
"strings"
)
func main(){
s := "Hello World"
fmt.Println(strings.NewReplacer("Hello"," ").Replace(s))
fmt.Println(strings.NewReplacer("World","").Replace(s))
}
Output:
World
Hello
Maybe there is an empty string keyword?
Even this works:
fmt.Println(strings.NewReplacer("ello", "").Replace(s))
This also works:
fmt.Println(strings.NewReplacer("Hello","", "Hi", "").Replace(s))
As orthopteroid mentioned, it seems single-replacement is special cased and buggy.
This was a bug. It is now fixed in tip.
https://groups.google.com/forum/#!topic/golang-nuts/CNdpwbCSbHM
And here is another way to remove substrings:
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Replace("Hello World", "Hello", "", 1))
}