Go语言查找字符串中单个字符

Go语言查找字符串中单个字符教程

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

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

IndexByte()函数

语法

func IndexByte(s string, c byte) int

参数

参数 描述
s 原字符串。
c 表示要检索的字符。

返回值

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

LastIndexByte()函数

语法

func LastIndexByte(s string, c byte) int

参数

参数 描述
s 原字符串。
c 表示要检索的字符。

返回值

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

案例

查找字符串中单个字符出现位置

使用 Strings.IndexByte() 函数,查找字符串中单个字符第一次出现位置

package main import ( "fmt" "strings" ) func main() { fmt.Println("嗨客网(www.haicoder.net)") //使用 Strings.IndexByte() 函数,查找字符序列中某个字符第一次出现的位置 strHaiCoder := "I love Golang and I study Golang From HaiCoder" indexByte := strings.IndexByte(strHaiCoder, 'l') fmt.Println("indexByte =", indexByte) }

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

28 golang查找字符串中单个字符.png

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

字符 l 第一次出现在了字符串的第 3 个位置,因此该函数返回了 2。

反向查找字符串中单个字符出现位置

使用 Strings.LastIndexByte() 函数,查找字符串中某个字符最后一次出现的位置

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

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

29 golang查找字符串中单个字符.png

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

字符 l 最后一次出现在了字符串的第 29 个位置,因此该函数返回了 28。

查找不存在的字符

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

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

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

30 golang查找字符串中单个字符.png

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

字符 c 不在我们要查找的字符串中,因此该函数返回了 -1。

Go语言查找字符串中单个字符总结

在 Go 语言中,在一个字符串中从开始查找一个字符我们使用 Strings.IndexByte() 函数,从结尾往前查找我们使用 Strings.LastIndexByte() 函数。Go 语言 IndexByte() 函数语法:

func IndexByte(s, chars string) int

Go 语言 LastIndexByte() 函数语法:

func LastIndexByte(s, chars string) int