在 Go 语言 中,在一个 字符串 中从开始查找一个中文 字符 我们使用 Strings.IndexRune() 函数,从结尾往前查找我们使用 Strings.LastIndexRune() 函数,而使用 Strings.IndexRune() 函数是不支持中文字符的查找的。
也就是说,Strings.IndexRune() 函数返回的是字符第一个出现的位置,而 Strings.LastIndexRune() 函数返回的是字符最后一次出现的位置。
func IndexRune(s string, r rune) int
参数 | 描述 |
---|---|
s | 原字符串。 |
r | 表示要检索的字符。 |
IndexRune() 函数返回 int 类型的值,如果包含,则返回第一次出现字符的索引;反之,则返回 -1。
func LastIndexRune(s string, r rune) int
参数 | 描述 |
---|---|
s | 原字符串。 |
r | 表示要检索的字符。 |
LastIndexRune() 函数返回 int 类型的值,如果包含,则返回最后一次出现字符序列的索引;反之,则返回 -1。
使用 Strings.IndexRune() 函数,查找字符串中中文字符第一次出现位置
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用 Strings.IndexRune() 函数,查找字符串中中文字符第一次出现位置
strHaiCoder := "I love Golang and I study Golang From 嗨客网"
indexRune := strings.IndexRune(strHaiCoder, '客')
fmt.Println("indexRune =", indexRune)
}
程序运行后,控制台输出如下:
首先,我们定义了一个字符串类型的 变量 strHaicoder,接着我们使用字符串的 strings.IndexRune() 函数查找字符串变量 strHaicoder 中中文字符 客 第一次出现的位置,并使用 print() 函数,打印最终的结果。
使用 Strings.LastIndexRune() 函数,查找字符串中某个中文字符最后一次出现的位置
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用 Strings.LastIndexRune() 函数,查找字符串中某个中文字符最后一次出现的位置
strHaiCoder := "I love Golang and I study Golang From 嗨客网"
lastIndexRune := strings.IndexRune(strHaiCoder, '客')
fmt.Println("lastIndexRune =", lastIndexRune)
}
程序运行后,控制台输出如下:
首先,我们定义了一个字符串类型的变量 strHaicoder,接着我们使用字符串的 strings.LastIndexRune() 函数查找字符串变量 strHaicoder 中中文字符 客 最后一次出现的位置,并使用 print() 函数,打印最终的结果。
使用 Strings.IndexRune() 函数,查找不存在的字符返回 -1
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用 Strings.IndexRune() 函数,查找不存在的字符返回 -1
strHaiCoder := "I love Golang and I study Golang From HaiCoder"
IndexRune := strings.IndexRune(strHaiCoder, 'c')
fmt.Println("IndexRune =", IndexRune)
}
程序运行后,控制台输出如下:
首先,我们定义了一个字符串类型的变量 strHaicoder,接着我们使用字符串的 strings.IndexRune() 函数查找字符串变量 strHaicoder 中中文字符 c 第一次出现的位置,并使用 print() 函数,打印最终的结果。
字符 c 不在我们要查找的字符串中,因此该函数返回了 -1。
在 Go 语言中,在一个字符串中从开始查找一个中文字符我们使用 Strings.IndexRune() 函数,从结尾往前查找我们使用 Strings.LastIndexRune() 函数。Go 语言 IndexRune() 函数语法:
func IndexRune(s string, r rune) int
Go 语言 LastIndexRune() 函数语法:
func LastIndexRune(s string, r rune) int