Go语言反向查找字符串

Go语言反向查找字符串教程

Go 语言 中,在一个 字符串 中从开始查找另一个字符串我们使用 Strings.Index() 函数,从结尾往前查找我们使用 Strings.LastIndex() 函数

也就是说,Strings.Index() 函数返回的是字符串第一个出现的位置,而 Strings.LastIndex() 函数返回的是字符串最后一次出现的位置。

LastIndex()函数

语法

func LastIndex(s, substr string) int

参数

参数 描述
s 原字符串。
substr 要检索的字符串。

返回值

LastIndex() 函数返回 int 类型的值,如果包含,则返回最后一次出现该字符串的索引;反之,则返回 -1。

案例

查找单个字符

使用 Strings.LastIndex() 函数,统计字符串某个字符最后一次出现的位置

package main import ( "fmt" "strings" ) func main() { fmt.Println("嗨客网(www.haicoder.net)") //使用 Strings.LastIndex() 函数,统计字符串某个字符最后一次出现的位置 strHaiCoder := "I love Golang and I study Golang From HaiCoder" lastIndex := strings.LastIndex(strHaiCoder, "l") fmt.Println("lastIndex =", lastIndex) }

程序运行后,控制台输出如下:

22 golang反向查找字符串.png

首先,我们定义了一个字符串类型的 变量 strHaicoder,接着我们使用字符串的 strings.LastIndex() 函数查找字符串变量 strHaicoder 中单个字符 l 最后一次出现的位置,并使用 print() 函数,打印最终的结果。

字符 l 在变量 strHaicoder 中最后一次出现在了第 29 个位置,所以返回了 28。

查找字符串

使用 Strings.Index() 函数,统计字符串某个字符串最后一次出现的位置

package main import ( "fmt" "strings" ) func main() { fmt.Println("嗨客网(www.haicoder.net)") //使用 Strings.Index() 函数,统计字符串某个字符串最后一次出现的位置 strHaiCoder := "I love Golang and I study Golang From HaiCoder" lastIndex := strings.LastIndex(strHaiCoder, "Golang") fmt.Println("lastIndex =", lastIndex) }

程序运行后,控制台输出如下:

23 golang反向查找字符串.png

首先,我们定义了一个字符串类型的变量 strHaicoder,接着我们使用字符串的 Strings.LastIndex() 函数查找字符串变量 strHaicoder 中字符串 Golang 最后一次出现的位置,并使用 print() 函数,打印最终的结果。

字符串 Golang 在变量 strHaicoder 中最后一次出现在了第 27 个位置,所以返回了 26。

查找不存在的字符串

使用 Strings.LastIndex() 函数,查找不存在的字符串返回 -1

package main import ( "fmt" "strings" ) func main() { fmt.Println("嗨客网(www.haicoder.net)") //使用 Strings.LastIndex() 函数,查找不存在的字符串返回 -1 strHaiCoder := "I love Golang and I study Golang From HaiCoder" lastIndex := strings.Index(strHaiCoder, "Haicoder") fmt.Println("lastIndex =", lastIndex) }

程序运行后,控制台输出如下:

24 golang反向查找字符串.png

首先,我们定义了一个字符串类型的变量 strHaicoder,接着我们使用字符串的 Strings.LastIndex() 函数查找字符串变量 strHaicoder 中字符串 Haicoder 最后一次出现的位置,并使用 print() 函数,打印最终的结果。

字符串 Haicoder 在变量 strHaicoder 中不存在,所以返回了 -1。

Go语言反向查找字符串总结

Strings.Index() 函数返回的是字符串第一个出现的位置,而 Strings.LastIndex() 函数返回的是字符串最后一次出现的位置。Go 语言 Strings.LastIndex() 系列函数语法:

func LastIndex(s, substr string) int