如何在 Go 語言中使用 ContainsAny() 函式?


Go 語言有一個內建的字串函式,稱為 ContainsAny(),我們可以使用它來檢查某個指定字串是否存在於給定的字串中。

ContainsAny() 與 Contains() 完全不同。

  • Contains() 用於檢測字串是否包含子字串。

  • ContainsAny() 用於檢測字串是否包含提供的字串中的任何字元。即使指定字串的一個字元存在於原始給定的字串中,它也會返回 True,否則返回 False。

語法

func ContainsAny(s, chars string) bool

其中,

  • s – 原始字串

  • chars string – 我們在其中定義字串或字元的子字串。

它返回一個布林值。

示例

ContainsAny() 區分大小寫,以下示例對此進行了說明。

package main
import (
   "fmt"
   "strings"
)
func main() {
   // Initializing the Strings
   x := "golang programming"
   y := "GO"
   
   // using the ContainsAny
   opt := strings.ContainsAny(x, y)
   
   // Display the ContainsAny Output
   fmt.Println("ContainsAny :", opt)
}

輸出

它將生成以下輸出 −

ContainsAny : false

請注意,該字串包含來自子字串的字元,但由於大小寫不匹配,ContainsAny 返回 False。

示例

我們再舉一個例子 −

package main
// importing fmt and strings
import (
   "fmt"
   "strings"
)
func main() {
   // Initializing the Strings
   p := "Function"
   q := "Programming"
   r := "language"
   s := "method"
   
   // using the ContainsAny
   test1 := strings.ContainsAny(p, q)
   test2 := strings.ContainsAny(r, s)
   test3 := strings.ContainsAny(s, p)
   test4 := strings.ContainsAny(q, s)
   
   // Display the ContainsAny Output
   fmt.Println("ContainsAny of test1 :", test1)
   fmt.Println("ContainsAny of test2 :", test2)
   fmt.Println("ContainsAny of test3 :", test3)
   fmt.Println("ContainsAny of test4 :", test4)
}

輸出

執行後,它將生成以下輸出 −

ContainsAny of test1 : true
ContainsAny of test2 : true
ContainsAny of test3 : true
ContainsAny of test4 : true

更新於: 2022 年 3 月 14 日

794 次瀏覽

開始您的 職業

完成課程獲取認證

開始
廣告