Golang strings.IndexByte()函数

Golang strings.IndexByte()函数

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

语法

func IndexByte(str string, chr byte) int
Go

其中。

  • str – 它是原始的字符串。
  • chr – 要检查字符串中的字符(字节)。

例子1

让我们考虑下面的例子 –

package main
import (
   "fmt"
   "strings"
)
func main() {
   // Initializing the Strings
   m := "IndexByte String Function"
   n := "Golang IndexByte String Package"
   
   // Display the Strings
   fmt.Println("First String:", m)
   fmt.Println("Second String:", n)

   // Using the IndexByte Function
   output1 := strings.IndexByte(m, 'g')
   output2 := strings.IndexByte(m, 'r')
   output3 := strings.IndexByte(n, 'E')
   output4 := strings.IndexByte(n, '4')

   // Display the IndexByte Output
   fmt.Println("IndexByte of 'g' in the First String:", output1)
   fmt.Println("IndexByte of 'r' in the First String:", output2)
   fmt.Println("IndexByte of 'E' in the Second String:", output3)
   fmt.Println("IndexByte of '4' in the Second String:", output4)
}
Go

输出

在执行时,它将产生以下输出 —

First String: IndexByte String Function
Second String: Golang IndexByte String Package
IndexByte of 'g' in the First String: 15
IndexByte of 'r' in the First String: 12
IndexByte of 'E' in the Second String: -1
IndexByte of '4' in the Second String: -1
Go

例子2

让我们再举一个例子–

package main
import (
   "fmt"
   "strings"
)
func main() {
   // Defining the Variables
   var s string
   var cbyte byte
   var result int
   
   // Intializing the Strings
   s = "IndexByte String Function"
   cbyte = 'B'
   
   // Display the Input String
   fmt.Println("Given String:", s)
   
   // Using the IndexByte Function
   result = strings.IndexByte(s, cbyte)
   
   // Output of IndexByte
   fmt.Println("IndexByte of 'B' in the Given String:", result)
}
Go

输出

它将产生以下输出 –

Given String: IndexByte String Function
IndexByte of 'B' in the Given String: 5
Go

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册