strings.Replacer:位置相关的错误/功能问题吗?

huangapple go评论140阅读模式
英文:

strings.Replacer: position dependent bug/functionality?

问题

我得到了以下输出:

你好,世界
你好

使用以下代码:

package main

import(
	"fmt"
	"strings"
)

func main(){
	s := "你好,世界"
	fmt.Println(strings.NewReplacer("你好","").Replace(s))
	fmt.Println(strings.NewReplacer("世界","").Replace(s))
}

这是一个错误吗?有没有更好的方法来删除子字符串?

英文:

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?

答案1

得分: 2

这是一个错误。现在在最新版本中已经修复。

https://groups.google.com/forum/#!topic/golang-nuts/CNdpwbCSbHM

这里还有另一种删除子字符串的方法:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Replace("Hello World", "Hello", "", 1))
}
英文:

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

答案2

得分: 1

我不是Go专家,但我觉得这看起来像是一个错误。

这个代码是可以工作的:

package main

import(
    "fmt"
    "strings"
)

func main(){
    s := "Hello World"
    fmt.Println(strings.NewReplacer("Hello"," ").Replace(s))
    fmt.Println(strings.NewReplacer("World","").Replace(s))
}

输出结果是:

 World 
Hello

也许有一个空字符串的关键字?

甚至这个也可以工作:

fmt.Println(strings.NewReplacer("ello", "").Replace(s))

这个也可以工作:

fmt.Println(strings.NewReplacer("Hello","", "Hi", "").Replace(s))

正如orthopteroid提到的,似乎单个替换是特殊情况并且有bug。

英文:

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.

huangapple
  • 本文由 发表于 2013年10月25日 05:09:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/19576693.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定