Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

go
golang
communitycreator

What is strings.IndexByte() in Go?

Siddharth Singh

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 c in the input string s.

  • If the byte c does not exist in s, then it returns -1.

Code

First, we imported the fmt and strings package to our program in the code below:

package main
import (
"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 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.

RELATED TAGS

go
golang
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring