在Go语言字符串中,可以使用以下函数从原始字符串中找到指定字符串的第一个索引值。这些函数是在字符串包下定义的,因此,您必须在程序中导入strings包才能使用这些功能:
1.Index:此函数用于从原始字符串中查找给定字符串的第一个实例的索引值。如果给定的字符串在原始字符串中不存在,则此方法将返回-1。
语法:
func Index(str, sbstr string) int
在这里,str是原始字符串,sbstr是我们要查找索引值的字符串。让我们借助示例来讨论这个概念:
示例
//给定字符串的索引值
package main
import (
"fmt"
"strings"
)
func main() {
//创建和初始化字符串
str1 := "Welcome to the online portal of sfjvip"
str2 := "My dog name is Dollar"
str3 := "I like to play Ludo"
//显示字符串
fmt.Println("字符串 1: ", str1)
fmt.Println("字符串 2: ", str2)
fmt.Println("字符串 3: ", str3)
//查找给定字符串的索引值
//使用Index()函数
res1 := strings.Index(str1, "Geeks")
res2 := strings.Index(str2, "do")
res3 := strings.Index(str3, "chess")
res4 := strings.Index("sfjvip, geeks", "ks")
//显示结果
fmt.Println("\n索引值:")
fmt.Println("结果 1: ", res1)
fmt.Println("结果 2: ", res2)
fmt.Println("结果 3: ", res3)
fmt.Println("结果 4: ", res4)
}
输出:
字符串 1: Welcome to the online portal of sfjvip
字符串 2: My dog name is Dollar
字符串 3: I like to play Ludo
索引值:
结果 1: -1
结果 2: 3
结果 3: -1
结果 4: 10
2. IndexAny:此方法从原始字符串中的chars返回任何Unicode码的第一个实例的索引值。如果原始字符中没有来自chars的Unicode代码点,则此方法将返回-1。
语法:
func IndexAny(str, charstr string) int
在这里,str是原始字符串,charstr是chars的Unicode代码点,我们想要查找索引值。
示例
//给定字符串的索引值
package main
import (
"fmt"
"strings"
)
func main() {
//创建和初始化字符串
str1 := "Welcome to the online portal of feishuai.vip"
str2 := "My dog name is Dollar"
str3 := "I like to play Ludo"
//显示字符串
fmt.Println("字符串 1: ", str1)
fmt.Println("字符串 2: ", str2)
fmt.Println("字符串 3: ", str3)
//查找给定的字符串索引值
//使用IndexAny()函数
res1 := strings.IndexAny(str1, "G")
res2 := strings.IndexAny(str2, "do")
res3 := strings.IndexAny(str3, "lqxa")
res4 := strings.IndexAny("sfjvip, geeks", "uywq")
//显示结果
fmt.Println("\n索引值:")
fmt.Println("结果 1: ", res1)
fmt.Println("结果 2: ", res2)
fmt.Println("结果 3: ", res3)
fmt.Println("结果 4: ", res4)
}
输出:
字符串 1: Welcome to the online portal of feishuai.vip
字符串 2: My dog name is Dollar
字符串 3: I like to play Ludo
索引值:
结果 1: -1
结果 2: 3
结果 3: 2
结果 4: -1
3. IndexByte:此函数返回原始字符串中给定字节的第一个实例的索引。如果给定的字节在原始字符串中不存在,则此方法将返回-1。
语法:
func IndexByte(str string, b byte) int
在这里,str是原始字符串,b是一个字节,我们要查找其索引值。让我们借助示例来讨论这个概念:
示例
// 给定字节的索引值
package main
import (
"fmt"
"strings"
)
// Main function
func main() {
//创建和初始化字符串
str1 := "Welcome to the online portal of feishuai.vip"
str2 := "My dog name is Dollar"
str3 := "I like to play Ludo"
// 显示字符串
fmt.Println("字符串 1: ", str1)
fmt.Println("字符串 2: ", str2)
fmt.Println("字符串 3: ", str3)
//查找给定字节的索引值
//使用IndexByte()函数
res1 := strings.IndexByte(str1, 'c')
res2 := strings.IndexByte(str2, 'o')
res3 := strings.IndexByte(str3, 'q')
res4 := strings.IndexByte("sfjvip, geeks", 'G')
//显示结果
fmt.Println("\n索引值:")
fmt.Println("结果 1: ", res1)
fmt.Println("结果 2: ", res2)
fmt.Println("结果 3: ", res3)
fmt.Println("结果 4: ", res4)
}
输出:
字符串 1: Welcome to the online portal of sfjvip
字符串 2: My dog name is Dollar
字符串 3: I like to play Ludo
索引值:
结果 1: 3
结果 2: 4
结果 3: -1
结果 4: 0