3.3 GO字符串处理

strings方法

index

判断子字符串或字符在父字符串中出现的位置(索引)
Index 返回字符串 str 在字符串 s 中的索引( str 的第一个字符的索引),-1 表示字符串 s 不包含
字符串 str :
strings.Index(s, str string) int
LastIndex 返回字符串 str 在字符串 s 中最后出现位置的索引( str 的第一个字符的索引),-1 表示
字符串 s 不包含字符串 str :
strings.LastIndex(s, str string) int
如果 ch 是非 ASCII 编码的字符,建议使用以下函数来对字符进行定位:
strings.IndexRune(s string, ch int) int

func test12(){
    var str string = "学习,就是知已不足,寻找改变的方法,尝试尝试再尝试,并以此为乐...这就是学习"
    fmt.Printf("The position of \"方法\" is: ")
    fmt.Printf("%d\n", strings.Index(str, "方法"))
    fmt.Printf("The position of the first instance of \"学习\" is: ")
    fmt.Printf("%d\n", strings.Index(str, "学习"))
    fmt.Printf("The position of the last instance of \"学习\" is: ")
    fmt.Printf("%d\n", strings.LastIndex(str, "学习"))
    fmt.Printf("The position of \"哪怕改变再小\" is: ")
    fmt.Printf("%d\n", strings.Index(str, "哪怕改变再小"))
}

输出

The position of "方法" is: 45
The position of the first instance of "学习" is: 0
The position of the last instance of "学习" is: 105
The position of "哪怕改变再小" is: -1

猜你喜欢

转载自www.cnblogs.com/perfei/p/12262763.html
3.3