Golang 中的 strings.IndexAny() 函数
strings.IndexAny 是 Golang 中的一个内置函数,用于获取输入子字符串中任何 Unicode 代码点的第一个实例的索引。如果找到子字符串,它将从 0 开始返回位置;否则,它将返回 -1。
语法
func IndexAny(s, chars string) int
其中,
- 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)
}输出
它将生成以下输出 -
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"。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言教程
C++
C #
MongoDB
MySQL
Javascript
PHP