如何在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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP