這是我的示例代碼: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 關注
- 176 瀏覽
添加回答
舉報
0/150
提交
取消