strings.Contains和strings.ContainsAny在Golang中的区别是什么?

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

Differences between strings.Contains and strings.ContainsAny in Golang

问题

在源代码中:

<!-- language: go -->

// Contains返回true,如果substr在s中。
func Contains(s, substr string) bool {
	return Index(s, substr) &gt;= 0
}

// ContainsAny返回true,如果chars中的任何Unicode代码点在s中。
func ContainsAny(s, chars string) bool {
	return IndexAny(s, chars) &gt;= 0
}

唯一的区别似乎是substrchars中的Unicode代码点。我编写了一些测试来测试它们两个。它们的行为似乎是相同的。我不明白何时使用哪个。

英文:

In the source code:

<!-- language: go -->

// Contains returns true if substr is within s.
func Contains(s, substr string) bool {
	return Index(s, substr) &gt;= 0
}

// ContainsAny returns true if any Unicode code points in chars are within s.
func ContainsAny(s, chars string) bool {
	return IndexAny(s, chars) &gt;= 0
}

the only difference seems to be substr and the Unicode code points in chars. I wrote some test to test both of them. Their behaviors seem to be identical. I don't understand when to use which.

答案1

得分: 12

我认为这两个函数完全不同。Contains函数用于检测一个字符串是否包含子字符串。ContainsAny函数用于检测一个字符串是否包含提供的字符串中的任何字符。

英文:

I think two functions are totally different. Contains are used to detect if a string contains a substring. ContainsAny are used to detect if a string contains any chars in the provided string.

答案2

得分: 0

Contains函数用于判断一个子字符串是否在字符串中。而ContainsAny函数用于判断字符串中是否包含任何Unicode字符。请查看文档

func main() {
    fmt.Println(strings.Contains("seafood", "aes"))
    fmt.Println(strings.ContainsAny("seafood", "aes"))
    fmt.Println(strings.Contains("iiii", "ui"))
    fmt.Println(strings.ContainsAny("iiii", "ui"))
}

输出结果为:

false
true
false
true
英文:

Contains function reports whether a sub-string is within the string. Whereas ContainsAny function reports whether any Unicode code points in chars are within the string. Look at the documentation.

 func main() {
     fmt.Println(strings.Contains(&quot;seafood&quot;, &quot;aes&quot;))
     fmt.Println(strings.ContainsAny(&quot;seafood&quot;, &quot;aes&quot;))
     fmt.Println(strings.Contains(&quot;iiii&quot;, &quot;ui&quot;))
     fmt.Println(strings.ContainsAny(&quot;iiii&quot;, &quot;ui&quot;))
 }

The output is;

false
true
false
true

huangapple
  • 本文由 发表于 2015年6月20日 22:04:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/30954852.html
匿名

发表评论

匿名网友

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

确定