这是我的示例代码: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这里的逻辑是当我输入路径和文件夹名(或文件名)时,我想知道该路径中文件夹名(或文件名)的级别。我这样做:将路径拆分为数组获取路径中文件夹名(或文件名)的索引如果索引为 0,则级别为 1,依此类推。
3 回答

猛跑小猪
TA贡献1858条经验 获得超8个赞
您可能需要遍历切片并找到您要查找的元素。
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。

慕姐8265434
TA贡献1813条经验 获得超2个赞
标准库中没有可用于在字符串切片中搜索的内置函数,但如果对字符串切片进行排序,则可以使用它sort.SearchStrings
进行搜索。但是在未排序的字符串切片的情况下,您必须使用 for 循环来实现它。
- 3 回答
- 0 关注
- 182 浏览
添加回答
举报
0/150
提交
取消