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

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

LastIndex() 是Golang中 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程