如何在 Golang 中找到字符串的索引?

阅读 351 收藏 0 点赞 0 评论 0

Strings.Index是 Golang 中的内置函数,它返回给定字符串中子字符串的第一个实例的索引。如果子字符串在给定字符串中不可用,则返回 -1。

语法

的语法Index()如下 -

func Index(s, substring string) int

在哪里,

  • s - 原始给定字符串

  • substring – 它是我们需要找到其索引值的字符串

示例 1

让我们考虑以下示例 -

package main
import (
   "fmt"
   "strings"
)
//主功能
func main() {
   
   //初始化字符串
   x := "Learn Golang on Nhooo"

   //显示字符串
   fmt.Println("给定字符串:", x)

   //使用索引功能
   result1 := strings.Index(x, "Golang")
   result2 := strings.Index(x, "nhooo")

   //显示索引输出
   fmt.Println("Index of 'Golang' in the 给定字符串:", result1)
   fmt.Println("Index 'nhooo' in the 给定字符串:", result2)
}
输出结果

它将产生以下输出 -

给定字符串: Learn Golang on Nhooo
Index of 'Golang' in the 给定字符串: 6
Index 'nhooo' in the 给定字符串: -1

请注意,该Index()函数区分大小写。这就是为什么它将 nhooo 的索引返回为 -1。

示例 2

让我们再举一个例子。

package main
import (
   "fmt"
   "strings"
)
func main() {
   
   //初始化字符串
   p := "Index String Function"
   q := "String Package"

   //显示字符串
   fmt.Println("第一个字符串:", p)
   fmt.Println("第二个字符串:", q)

   //使用索引功能
   output1 := strings.Index(p, "Function")
   output2 := strings.Index(q, "Package")

   //显示索引输出
   fmt.Println("Index of 'Function' in the 1st String:", output1)
   fmt.Println("Index of 'Package' in the 2nd String:", output2)
}
输出结果

它将生成以下输出 -

第一个字符串: Index String Function
第二个字符串: String Package
Index of 'Function' in the 1st String: 13
Index of 'Package' in the 2nd String: 7

评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号