如何在 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

更新時間: 2022 年 3 月 10 日

12K+ 瀏覽量

開啟您的 職業

完成教程,獲得認證

立即開始
廣告
© . All rights reserved.