ContainsRune给出了奇怪的结果

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

ContainsRune giving strange results

问题

我正在Go Playground中运行这段代码:

fmt.Println(strings.ContainsRune("\xa0", '\xa0'))

我想知道为什么它输出false?根据文档,它说:

如果Unicode码点r在s中,则ContainsRune返回true。

在我看来,该码点确实存在,所以它给出false作为响应似乎很奇怪。

英文:

I'm running this code in Go Playground:

fmt.Println(strings.ContainsRune("\xa0", '\xa0'))

I'm wondering, why does it output false? According to the docs, it says:

> ContainsRune returns true if the Unicode code point r is within s.

It seems to me that the code point is there, it seems strange that it would give false as a response.

答案1

得分: 5

"\x0a" 不是一个 Unicode 代码点。

fmt.Println(strings.ContainsRune("\u00a0", '\u00a0'))

按预期工作。

英文:

"\x0a" is not a unicode code point.

fmt.Println(strings.ContainsRune("\u00a0", '\u00a0'))

Works, as expected.

答案2

得分: 3

因为它不是一个有效的Unicode代码点,所以可以查看strings.IndexRune函数的实现。

func IndexRune(s string, r rune) int {
    switch {
    case r < 0x80:
        .....
    default:
        .....
    }
    return -1
}

如果你尝试使用utf8.ValidString("\xa0"),它会返回false。

英文:

Because it's not a valid unicode code point, looking at strings.IndexRune

func IndexRune(s string, r rune) int {
	switch {
	case r &lt; 0x80:
		.....
	default:
		.....
	}
	return -1
}

If you try utf8.ValidString(&quot;\xa0&quot;) it will return false.

huangapple
  • 本文由 发表于 2014年9月11日 05:01:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/25775022.html
匿名

发表评论

匿名网友

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

确定