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

huangapple go评论137阅读模式
英文:

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

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

我通过以下步骤实现:

  1. 将路径拆分为数组
  2. 获取文件夹名(或文件名)在路径中的索引

如果索引为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:

  1. Split the path to an array
  2. 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.

huangapple
  • 本文由 发表于 2022年1月25日 11:04:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/70842972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定