Golang中的strings.LastIndex()函數返回給定字符串中子字符串的最後一個實例出現的起始索引。如果未找到子字符串,則返回-1。因此,此函數返回一個整數值。索引以零作為字符串的起始索引進行計數。
用法:
func LastIndex(str, substring string) int
在這裏,str是原始字符串,substring是一個字符串,我們要查找其最後一個索引值。
範例1:
// Golang program to illustrate the
// strings.LastIndex() Function
package main
import (
"fmt"
"strings"
)
func main() {
// taking a string
str:= "GeeksforGeeks"
substr:= "Geeks"
fmt.Println(strings.LastIndex(str, substr))
}
輸出:
8
字符串是“GeeksforGeeks”,子字符串是“Geeks”,因此編譯器會找到原始字符串中存在的子字符串,並顯示該子字符串的最後一個實例的起始索引為8。
範例2:
// Golang program to illustrate the
// strings.LastIndex() Function
package main
import (
"fmt"
"strings"
)
func main() {
// taking strings
str:= "My favorite sport is football"
substr1:= "f"
substr2:= "ll"
substr3:= "SPORT"
// using the function
fmt.Println(strings.LastIndex(str, substr1))
fmt.Println(strings.LastIndex(str, substr2))
fmt.Println(strings.LastIndex(str, substr3))
}
輸出:
21 27 -1
字符串為“我最喜歡的運動是足球”,子字符串為“f”,“ll”和“SPORT”,因此編譯器在前兩種情況下分別將輸出顯示為21和27,並且由於第三個子字符串為“SPORT”,因此認為在輸出項中不存在該子字符串。字符串,因為該函數區分大小寫,因此結果為-1。
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自prakhar7大神的英文原創作品 strings.LastIndex() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。