strings.Index() Golang中的函數用於獲取指定子字符串的第一個實例。如果未找到子字符串,則此方法將返回-1。
用法:
func Index(str, sbstr string) int
在這裏,str是原始字符串,sbstr是我們要查找索引值的字符串。
範例1:
// Go program to illustrate the
// String Index() Function
package main
import (
"fmt"
"strings"
)
// Main function
func main() {
// Creating and initializing the strings
str1:= "Welcome to GeeksforGeeks"
str2:= "My name is XYZ"
// Displaying strings
fmt.Println("String 1:", str1)
fmt.Println("String 2:", str2)
// Using Index() function
res1:= strings.Index(str1, "Geeks")
res2:= strings.Index(str2, "is")
// Displaying the result
fmt.Println("\nIndex values:")
fmt.Println("Result 1:", res1)
fmt.Println("Result 2:", res2)
}
輸出:
String 1: Welcome to GeeksforGeeks String 2: My name is XYZ Index values: Result 1: 11 Result 2: 8
範例2:
// Go program to illustrate the
// String Index() Function
package main
import (
"fmt"
"strings"
)
// Main function
func main() {
// Using Index() function
res1:= strings.Index("GFG", "H")
res2:= strings.Index("GeeksforGeeks", "for")
// Displaying the result
fmt.Println("Result 1:", res1)
fmt.Println("Result 2:", res2)
}
輸出:
Result 1: -1 Result 2: 5
相關用法
- 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()用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 strings.Index() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。