golang 是一门效率和性能非常高的程序语言,在字符串操作上也不例外。如果需要在 golang 中查找一个字符串的子串位置,可以使用标准库中的 strings 包提供的函数来实现。
下面是 golang 中求子串位置的几种方法:
1. strings.index 函数package mainimport (    "fmt"    "strings")func main() {    str := "hello, world"    substr := "world"    index := strings.index(str, substr)    fmt.println("substr in str:", index)}
运行结果:
substr in str: 7
strings.index 函数返回子串在字符串中第一次出现的位置,如果子串不在字符串中则返回 -1。
2. strings.lastindex 函数strings.lastindex 函数和 strings.index 函数类似,但是是从字符串末尾开始查找子串。
package mainimport (    "fmt"    "strings")func main() {    str := "hello, world, world"    substr := "world"    index := strings.lastindex(str, substr)    fmt.println("substr in str:", index)}
运行结果:
substr in str: 13
3. strings.indexany 函数strings.indexany 函数用于查找子串中任意一个字符在字符串中首次出现的位置。
package mainimport (    "fmt"    "strings")func main() {    str := "hello, world"    substr := "ow"    index := strings.indexany(str, substr)    fmt.println("substr in str:", index)}
运行结果:
substr in str: 4
4. strings.indexbyte 函数strings.indexbyte 函数用于查找子串中指定字节在字符串中首次出现的位置。
package mainimport (    "fmt"    "strings")func main() {    str := "hello, world"    substr := ','    index := strings.indexbyte(str, substr)    fmt.println("substr in str:", index)}
运行结果:
substr in str: 5
5. strings.indexfunc 函数strings.indexfunc 函数用于查找子串中满足指定条件的字符在字符串中首次出现的位置。
package mainimport (    "fmt"    "strings")func main() {    str := "hello, world"    substr := func(r rune) bool {        return r == 'l'    }    index := strings.indexfunc(str, substr)    fmt.println("substr in str:", index)}
运行结果:
substr in str: 2
以上就是 golang 中求子串位置的几种方法,根据不同情况选用适合的方式可以有效提高程序的效率。
以上就是golang 求子串位置的详细内容。
   
 
   