如何在 Go 语言中查找字符串的索引?
Strings.Index 是 Go 语言中内置的一个函数,可返回给定字符串中子字符串第一次出现的索引。如果给定的字符串中没有子串,则返回 -1。
语法
Index() 的语法如下 −
func Index(s, substring string) int
其中,
- s – 原始给定字符串
- substring – 需要查找其索引值字符串
示例 1
考虑一下下面的示例 −
package main
import (
"fmt"
"strings"
)
// Main function
func main() {
// Initializing the Strings
x := "Learn Golang on Tutorialspoint"
// Display the Strings
fmt.Println("Given String:", x)
// Using the Index Function
result1 := strings.Index(x, "Golang")
result2 := strings.Index(x, "TUTORIALSPOINT")
// Display the Index Output
fmt.Println("Index of 'Golang' in the Given String:", result1)
fmt.Println("Index 'TUTORIALSPOINT' in the Given String:", result2)
}输出
它会生成以下输出 −
Given String: Learn Golang on Tutorialspoint Index of 'Golang' in the Given String: 6 Index 'TUTORIALSPOINT' in the Given String: -1
请注意,Index() 函数是大小写敏感的。这就是为什么它将 TUTORIALSPOINT 的索引返回为 -1。
示例 2
让我们看另一个示例。
package main
import (
"fmt"
"strings"
)
func main() {
// Initializing the Strings
p := "Index String Function"
q := "String Package"
// Display the Strings
fmt.Println("First String:", p)
fmt.Println("Second String:", q)
// Using the Index Function
output1 := strings.Index(p, "Function")
output2 := strings.Index(q, "Package")
// Display the Index Output
fmt.Println("Index of 'Function' in the 1st String:", output1)
fmt.Println("Index of 'Package' in the 2nd String:", output2)
}输出
它会生成以下输出 −
First String: Index String Function Second String: String Package Index of 'Function' in the 1st String: 13 Index of 'Package' in the 2nd String: 7
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP