Home »
Golang »
Golang Reference
Golang strings.IndexByte() Function with Examples
Golang | strings.IndexByte() Function: Here, we are going to learn about the IndexByte() function of strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 16, 2021
strings.IndexByte()
The IndexByte() function is an inbuilt function of strings package which is used to get the index of the first occurrence (instance) of a character (byte) in string. It accepts two parameters – string and a character (byte) and returns the index, or -1 if the byte is not present in the string.
Syntax
func IndexByte(str string, chr byte) int
Parameters
- str : String in which we have to check the byte.
- chr : Character (byte) to be checked in the string.
Return Value
The return type of IndexByte() function is a bool, it returns the index of the first occurrence (instance) of character (byte) in the string, or -1 if the character (byte) is not present in the string.
Example 1
// Golang program to demonstrate the
// example of strings.IndexByte() Function
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.IndexByte("Hello, world", 'w'))
fmt.Println(strings.IndexByte("Hello, world", 'x'))
fmt.Println(strings.IndexByte("Okay@123", '@'))
}
Output:
7
-1
4
Example 2
// Golang program to demonstrate the
// example of strings.IndexByte() Function
package main
import (
"fmt"
"strings"
)
func main() {
var str string
var chr byte
var index int
str = "Hello, world!"
chr = 'w'
index = strings.IndexByte(str, chr)
if index >= 0 {
fmt.Printf("%c found in %q at %d index.\n", chr, str, index)
} else {
fmt.Printf("%c does not found in %q.\n", chr, str)
}
str = "Hello, world!"
chr = 'x'
index = strings.IndexByte(str, chr)
if index >= 0 {
fmt.Printf("%c found in %q at %d index.\n", chr, str, index)
} else {
fmt.Printf("%c does not found in %q.\n", chr, str)
}
str = "Okay@123"
chr = '@'
index = strings.IndexByte(str, chr)
if index >= 0 {
fmt.Printf("%c found in %q at %d index.\n", chr, str, index)
} else {
fmt.Printf("%c does not found in %q.\n", chr, str)
}
}
Output:
w found in "Hello, world!" at 7 index.
x does not found in "Hello, world!".
@ found in "Okay@123" at 4 index.
Golang strings Package Functions »