IndexByte()
methodThe 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.
func IndexByte(s string, c byte) int
This method takes a string s
and a byte c
as inputs.
This method returns the index of the first occurrence of the byte c
in the input string s
.
If the byte c
does not exist in s
, then it returns -1
.
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)}
After importing fmt
, we call the IndexByte()
method with "educative.io"
as the input string and byte 'c'
to search and get the index. This returns 3
, as 'c'
is present at index 3
in 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 the fmt
package.