Golang 中的 strings.IndexByte() 函数

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

IndexByte()是Golang中strings包的内置函数。此函数返回给定字符串中字符第一次出现的索引。如果找到该字符,则返回其索引,从 0 开始;否则返回“- 1 ”。

语法

func IndexByte(str string, chr byte) int

在哪里,

  • str - 它是原始字符串。

  • chr – 要在字符串中检查的字符(字节)。

示例 1

让我们考虑以下示例 -

package main
import (
   "fmt"
   "strings"
)
func main() {
   //初始化字符串
   m := "IndexByte String Function"
   n := "Golang IndexByte String Package"
   
   //显示字符串
   fmt.Println("第一个字符串:", m)
   fmt.Println("第二个字符串:", n)

   //使用 IndexByte 函数
   output1 := strings.IndexByte(m, 'g')
   output2 := strings.IndexByte(m, 'r')
   output3 := strings.IndexByte(n, 'E')
   output4 := strings.IndexByte(n, '4')

   //显示 IndexByte 输出
   fmt.Println("IndexByte of 'g' in the 第一个字符串:", output1)
   fmt.Println("IndexByte of 'r' in the 第一个字符串:", output2)
   fmt.Println("IndexByte of 'E' in the 第二个字符串:", output3)
   fmt.Println("IndexByte of '4' in the 第二个字符串:", output4)
}
输出结果

执行时,它将生成以下输出 -

第一个字符串: IndexByte String Function
第二个字符串: Golang IndexByte String Package
IndexByte of 'g' in the 第一个字符串: 15
IndexByte of 'r' in the 第一个字符串: 12
IndexByte of 'E' in the 第二个字符串: -1
IndexByte of '4' in the 第二个字符串: -1

示例 2

让我们再举一个例子 -

package main
import (
   "fmt"
   "strings"
)
func main() {
   //定义变量
   var s string
   var cbyte byte
   var result int
   
   //初始化字符串
   s = "IndexByte String Function"
   cbyte = 'B'
   
   //显示输入字符串
   fmt.Println("给定字符串:", s)
   
   //使用 IndexByte 函数
   result = strings.IndexByte(s, cbyte)
   
   //IndexByte 的输出
   fmt.Println("IndexByte of 'B' in the 给定字符串:", result)
}
输出结果

它将生成以下输出 -

给定字符串: IndexByte String Function
IndexByte of 'B' in the 给定字符串: 5

评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号