Home >Backend Development >Golang >golang finds substring position
golang is a programming language with very high efficiency and performance, and string operations are no exception. If you need to find the substring position of a string in golang, you can use the functions provided by the strings package in the standard library.
The following are several methods for finding the position of substrings in golang:
package main import ( "fmt" "strings" ) func main() { str := "hello, world" substr := "world" index := strings.Index(str, substr) fmt.Println("substr in str:", index) }
Running results:
substr in str: 7
strings.Index
The function returns the position of the first occurrence of the substring in the string. If the substring is not in the string, it returns -1
.
strings.LastIndex
function is similar to the strings.Index
function, but it searches for substrings starting from the end of the string. string.
package main import ( "fmt" "strings" ) func main() { str := "hello, world, world" substr := "world" index := strings.LastIndex(str, substr) fmt.Println("substr in str:", index) }
Run result:
substr in str: 13
strings.IndexAny
The function is used to find any character in the substring. The position of the first occurrence in the string.
package main import ( "fmt" "strings" ) func main() { str := "hello, world" substr := "ow" index := strings.IndexAny(str, substr) fmt.Println("substr in str:", index) }
Run result:
substr in str: 4
strings.IndexByte
The function is used to find the specified byte in the substring. The position of the first occurrence in the string.
package main import ( "fmt" "strings" ) func main() { str := "hello, world" substr := ',' index := strings.IndexByte(str, substr) fmt.Println("substr in str:", index) }
Run result:
substr in str: 5
strings.IndexFunc
The function is used to find characters in a substring that meet specified conditions. The position of the first occurrence in the string.
package main import ( "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) }
Run results:
substr in str: 2
The above are several methods for finding the substring position in golang. Choosing the appropriate method according to different situations can effectively improve the efficiency of the program.
The above is the detailed content of golang finds substring position. For more information, please follow other related articles on the PHP Chinese website!