Golang 如何找到一个字符串的索引

Golang 如何找到一个字符串的索引

Strings.Index 是Golang中的一个内置函数,用于返回一个给定字符串中子串的第一个实例的索引。如果子串在给定的字符串中不存在,那么它将返回-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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程