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:
- Split the path to an array
- 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.
CodePudding user response:
Use strings.IndexAny instead of bytes.IndexAny if you want to operate on a []string.
CodePudding user response:
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.
CodePudding user response:
there are no inbuild function available in standard library to search in slice of string, but if slice of string is sorted then you can use sort.SearchStrings to search. But in case of unsorted slice of string you have to implement it using for loop.
