英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论