Golang strings.IndexAny()函数

Golang strings.IndexAny()函数

strings.IndexAny 是Golang中的一个内置函数,用于从输入的子串中获取任何Unicode代码点的第一个实例的索引。如果找到该子串,它将返回从0开始的位置;否则将返回-1。

语法

func IndexAny(s, chars string) int
Go

其中。

  • s – 原始的给定字符串。
  • 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)
}
Go

输出

它将产生以下输出 –

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

请注意,子串中的字符 ” 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)
}
Go

输出

它将产生以下输出 –

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
Go

注意,给定的子串中的字符 ” l “和 ” p “在第一个字符串中不存在,因此 IndexAny() 返回” -1 “。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册