Golang 中的 strings.IndexByte() 函数
IndexByte() 是 Golang 中**字符串**包的一个内置函数。此函数返回给定字符串中首次出现的字符的索引。如果找到此字符,则返回其索引,从 0 开始;否则返回 "-1"。
语法
func IndexByte(str string, chr byte) int
其中,
- 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)
}输出
执行后,将生成以下输出 −
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
示例 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)
}输出
它将生成以下输出 −
Given String: IndexByte String Function IndexByte of 'B' in the Given String: 5
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP