如何获取数组中字符串的索引?

这是我的示例代码:

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

我收到了这个错误

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

这里的逻辑是当我输入路径和文件夹名(或文件名)时,我想知道该路径中文件夹名(或文件名)的级别。

我这样做:

  1. 将路径拆分为数组

  2. 获取路径中文件夹名(或文件名)的索引

如果索引为 0,则级别为 1,依此类推。


森栏
浏览 124回答 3
3回答

猛跑小猪

您可能需要遍历切片并找到您要查找的元素。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}请注意,循环是向后的,以解决 Burak Serdar 指出的逻辑问题,它可能会在其他路径上失败/a/a/a/a。

jeck猫

如果strings.IndexAny要bytes.IndexAny对[]string.

慕姐8265434

标准库中没有可用于在字符串切片中搜索的内置函数,但如果对字符串切片进行排序,则可以使用它sort.SearchStrings进行搜索。但是在未排序的字符串切片的情况下,您必须使用 for 循环来实现它。
打开App,查看更多内容
随时随地看视频慕课网APP