如何在Go語言中查詢字串的最後一個索引值?


**LastIndex()** 是Go語言**strings**包中的內建函式。此函式用於檢查給定原始字串中指定子字串最後一次出現的索引。如果在給定字串中找到子字串,則返回其索引位置(從0開始);否則返回“-1”。

語法

**LastIndex()** 的語法如下:

func LastIndex(str, substr string) int

其中,

  • **str** 是需要在其中搜索的字串,以及
  • **substr** 是要在**str**內部搜尋的子字串。

示例1

讓我們考慮以下示例:

package main
import (
   "fmt"
   "strings"
)
func main() {
   
   // Initializing the Strings
   p := "Programming Language"
   q := "String Function"
   r := "Golang String Function"
   s := "1234512345"

   // Display the Strings
   fmt.Println("String 1:", p)
   fmt.Println("String 2:", q)
   fmt.Println("String 3:", r)
   fmt.Println("String 4:", s)

   // Using the LastIndex Function
   test1 := strings.LastIndex(p, "ge")
   test2 := strings.LastIndex(q, "C")
   test3 := strings.LastIndex(r, "ng")
   test4 := strings.LastIndex(s, "23")

   // Display the LastIndex Output
   fmt.Println("LastIndex of 'ge' in String 1:", test1)
   fmt.Println("LastIndex of 'C' in String 2:", test2)
   fmt.Println("LastIndex of 'ng' in String 3:", test3)
   fmt.Println("LastIndex of '23' in String 4:", test4)
}

輸出

它將生成以下輸出:

String 1: Programming Language
String 2: String Function
String 3: Golang String Function
String 4: 1234512345
LastIndex of 'ge' in String 1: 18
LastIndex of 'C' in String 2: -1
LastIndex of 'ng' in String 3: 11
LastIndex of '23' in String 4: 6

請注意,**LastIndex()** 區分大小寫;因此,對於**test2**,它返回“**-1**”。

示例2

讓我們來看另一個例子。

package main
import (
   "fmt"
   "strings"
)
func main() {
   var x string
   var y string

   // Intializing the Strings
   x = "LastIndex"
   y = "LastIndex Function"

   // Display the Strings
   fmt.Println("String 1:", x)
   fmt.Println("String 2:", y)

   // See if y is found in x using LastIndex Function
   if strings.LastIndex(y, x) != -1 {
      fmt.Println("String 2 is found in String 1")
   } else {
      fmt.Println("String 2 is not found in String 1")
   }
}

輸出

它將生成以下輸出:

String 1: LastIndex
String 2: LastIndex Function
String 2 is found in String 1

更新於:2022年3月10日

4K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.