go stings.Index()方法
strings.Index()方法
Golang语言中的标准库strings模块中的Index()方法可以匹配查找子串在字符串中第一次出现的索引位置,如果字符串不存在该子串,则返回-1。
语法
func Index(s, sep string) int
go源码Index()方法的介绍:
Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.
参数
参数 | 描述 |
---|---|
s | string字符串类型 |
sep | 字符串string类型 |
返回值
子串sep在字符串s中的索引值,如果s中不包含子串sep,则返回-1。
strings.Index()方法实例代码
观察字母子串和中文子串的索引的区别:
func main() {
str := "ab,笨鸟工具,x1y1z1.com"
var I1 int = strings.Index(str, "b")
fmt.Println(I1)
I2 := strings.Index(str, "笨")
fmt.Println(I2)
I3 := strings.Index(str, "鸟")
fmt.Println(I3)
}
//命令行输入运行go文件的命令,比如:go run test.go,得到输出:
1
3
6