英文:
How to get the index of a string in an array?
问题
这是我的示例代码:
slice_of_string := strings.Split("root/alpha/belta", "/")
res1 := bytes.IndexAny(slice_of_string , "alpha")
我得到了这个错误:
./prog.go:16:24: 无法将类型 []string 作为参数传递给 bytes.IndexAny 中的类型 []byte
这里的逻辑是,当我输入一个路径和一个文件夹名(或文件名)时,我想知道该路径中文件夹名(或文件名)的级别。
我通过以下步骤实现:
- 将路径拆分为数组
- 获取文件夹名(或文件名)在路径中的索引
如果索引为0,则级别为1,依此类推。
英文:
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.
答案1
得分: 1
如果你想在[]string
上进行操作,可以使用strings.IndexAny
而不是bytes.IndexAny
。
英文:
Use strings.IndexAny
instead of bytes.IndexAny
if you want to operate on a []string
.
答案2
得分: 1
你可能需要循环遍历切片,并找到你要查找的元素。
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
这样的路径上失败。
英文:
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.
答案3
得分: 1
标准库中没有内置的函数可以在字符串切片中进行搜索,但如果字符串切片已排序,你可以使用sort.SearchStrings
进行搜索。但是,对于未排序的字符串切片,你需要使用for循环来实现搜索。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论