Golang 中的 strings.IndexAny() 函式


strings.IndexAny 是 Golang 中的一個內建函式,用於獲取輸入子字串中任何 Unicode 程式碼點的第一個例項的索引。如果找到子字串,它將從 0 開始返回位置;否則,它將返回 -1。

語法

func IndexAny(s, chars string) int

其中,

  • – 給定的原始字串。
  • chars – 將要在給定字串中檢查的子字串。

示例 1

請看下面的示例。

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Defining the Variables
   var str string
   var charstring string
   var text int

   // Intializing the Strings
   str = "IndexAny String Function"
   charstring = "Hyderabad"

   // Using the IndexAny Function
   text = strings.IndexAny(str, charstring)
   
   // Display the Strings
   fmt.Println("Given String:", str)
   fmt.Println("Substring:", charstring)

   // Output of IndexAny
   fmt.Println("IndexAny of Substring characters:", text)
}

輸出

它將生成以下輸出 -

Given String: IndexAny String Function
Substring: Hyderabad
IndexAny of Substring characters: 2

請注意,子字串中的字元 "d" 在給定字串中出現在索引 "2" 處。因此,IndexAny() 返回 "2"。

示例 2

我們再舉一個例子 -

package main
import (
   "fmt"
   "strings"
)
func main() {

   // Initializing the Strings
   x := "IndexAny String Function"
   y := "Golang Strings Package"
   
   // Display the Strings
   fmt.Println("First String:", x)
   fmt.Println("Second String:", y)

   // Using the IndexAny Function
   result1 := strings.IndexAny(x, "net")
   result2 := strings.IndexAny(x, "lp")
   result3 := strings.IndexAny(y, "Language")
   result4 := strings.IndexAny(y, "go")

   // Display the IndexAny Output
   fmt.Println("IndexAny of 'net' in the 1st String:", result1)
   fmt.Println("IndexAny of 'lp' in the 1st String:", result2)
   fmt.Println("IndexAny of 'Language' in the 2nd String:", result3)
   fmt.Println("IndexAny of 'go' in the 2nd String:", result4)
}

輸出

它將生成以下輸出 -

First String: IndexAny String Function
Second String: Golang Strings Package
IndexAny of 'net' in the 1st String: 1
IndexAny of 'lp' in the 1st String: -1
IndexAny of 'Language' in the 2nd String: 3
IndexAny of 'go' in the 2nd String: 1

請注意,給定子字串中的字元 "l" 和 "p" 不存在於第 1 個字串中,因此 IndexAny() 返回 "-1"。

更新日期:2022 年 3 月 10 日

278 次瀏覽

開始你的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.