What is strings.IndexByte() in Go?
The IndexByte() method
The IndexByte() method returns the index of first occurrence of the input byte in a given string.
The strings package is a Go standard library package that contains functions to manipulate UTF-8 encoded strings.
Syntax
func IndexByte(s string, c byte) int
Arguments
This method takes a string s and a byte c as inputs.
Return value
-
This method returns the index of the first occurrence of the byte
cin the input strings. -
If the byte
cdoes not exist ins, then it returns-1.
Code
First, we imported the fmt and strings package to our program in the code below:
package mainimport ("fmt""strings")func main() {str1 := "educative.io"fmt.Println("String : ", str1)index1 := strings.IndexByte(str1, 'c')index2 := strings.IndexByte(str1, 'z')fmt.Println("byte : 'c',", "Index : ", index1)fmt.Println("byte : 'z',", "Index : ", index2)}
Explanation
-
After importing
fmt, we call theIndexByte()method with"educative.io"as the input string and byte'c'to search and get the index. This returns3, as'c'is present at index3in the input string"eductive.io". -
We again call the
Index()method with"educative.io"as the input string and'z'as the byte to search and get the index. This returns-1, because'z'is not present in the input string"eductive.io". -
We show the output of all these operations using the
Println()method of thefmtpackage.