Home >Backend Development >Golang >Use the strings.LastIndex function to return the last occurrence of a specified substring in a string.
Use the strings.LastIndex function to return the last occurrence position of the specified substring in the string
In the Go language, strings are a very common data type, and we often need to process and operate. In some cases, we may need to obtain the last occurrence position of a certain substring in the string to perform corresponding subsequent processing. At this time, you can use the LastIndex function in the strings package to achieve this.
The prototype of the LastIndex function is as follows:
func LastIndex(s, substr string) int
This function receives two parameters, namely the string s to be searched and the substring to be searched. substr and returns the last occurrence of the substring in the string.
Below we use a specific example to demonstrate how to use the LastIndex function.
import (
"fmt" "strings"
)
func main() {
str := "Hello, Go Go Go!" substr := "Go" index := strings.LastIndex(str, substr) fmt.Printf("子串"%s"在字符串"%s"中最后出现的位置是:%d
", substr, str, index)
}
Run the above code, the output is as follows:
The last position where the substring "Go" appears in the string "Hello, Go Go Go!" is: 10
In the above code, we define A string str and a substring substr. Then the LastIndex function in the strings package is called, passing the string and substring as parameters, and assigning the return value to the index variable.
Finally, use the Printf function Output the result to the console.
As can be seen from the output result, the last position of the substring "Go" in the string "Hello, Go Go Go!" is 10.
In this way, we successfully use the strings.LastIndex function to obtain the last occurrence position of the specified substring in the string.
It should be noted that if the specified substring does not exist in the string, the LastIndex function will return -1. Therefore, when using this function, we need to judge the return value to ensure that there is a substring to be found in the string.
The above is the detailed content of Use the strings.LastIndex function to return the last occurrence of a specified substring in a string.. For more information, please follow other related articles on the PHP Chinese website!