Golang strings.Index()函数及示例
strings.Index()函数 在Golang中用于获取特定子字符串的第一个实例。如果未找到子字符串,则该方法将返回-1。
语法:
func Index(str, sbstr string) int
这里,str是原始字符串,sbstr是我们要查找索引值的字符串。
例1:
//演示strings.Index()函数的Go程序
package main
import (
"fmt"
"strings"
)
//主函数
func main() {
//创建并初始化字符串
str1 := "Welcome to GeeksforGeeks"
str2 := "My name is XYZ"
//显示字符串
fmt.Println("字符串1:", str1)
fmt.Println("字符串2:", str2)
//使用Index()函数
res1 := strings.Index(str1, "Geeks")
res2 := strings.Index(str2, "is")
//显示结果
fmt.Println("\n索引值:")
fmt.Println("结果1:", res1)
fmt.Println("结果2:", res2)
} ```
输出:
字符串1: Welcome to GeeksforGeeks
字符串2: My name is XYZ
索引值:
结果1: 11
结果2: 8
例2:
//演示strings.Index()函数的Go程序
package main
import (
"fmt"
"strings"
)
//主函数
func main() {
//使用Index()函数
res1 := strings.Index("GFG", "H")
res2 := strings.Index("GeeksforGeeks", "for")
//显示结果
fmt.Println("结果1:", res1)
fmt.Println("结果2:", res2)
}
输出:
结果1: -1
结果2: 5