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