How to get the index of a string in an array?

Issue

Here is my sample code:

slice_of_string := strings.Split("root/alpha/belta", "/")
res1 := bytes.IndexAny(slice_of_string , "alpha")

I got this error

./prog.go:16:24: cannot use a (type []string) as type []byte in argument to bytes.IndexAny

The logic here is when I input a path and a folder name (or file name), I want to know the level of the folder name (or a file name) in that path.

I do it by:

  1. Split the path to an array
  2. Get the index of the folder name (or a file name) in the path

If the index is 0 then the level would be 1, etc.

Solution

You probably need to loop over the slice and find the element that you are looking for.

func main() {
    path := "root/alpha/belta"
    key := "alpha"
    index := getIndexInPath(path, key)
    fmt.Println(index)
}

func getIndexInPath(path string, key string) int {
    parts := strings.Split(path, "/")
    if len(parts) > 0 {
        for i := len(parts) - 1; i >= 0; i-- {
            if parts[i] == key {
                return i
            }
        }
    }
    return -1
}

Note that the loop is backwards to address the logic issue that Burak Serdar pointed out that it may fail on a path like /a/a/a/a otherwise.

Answered By – Bazzz

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.