登录
首页 >  Golang >  Go问答

相当于indexOf

来源:stackoverflow

时间:2024-03-18 21:33:31 426浏览 收藏

在 Go 语言中,没有直接等同于 indexOf 的函数来查找数组中特定元素的位置。然而,您可以通过自定义函数或利用已排序数组的优势来实现类似的功能。

问题内容

我试图找出indexof的等价物来获取数组golang中特定元素的位置,从而达到数组中整数的目的。

package main

import (
    "fmt"
)

func main() {
    fmt.Println("what")

    arr := []int{1, 2, 3, 4, 2, 2, 3, 5, 4, 4, 1, 6}

    i := IndexOf(2, arr)

}

解决方案


go 中没有 indexof 的等效项。您需要自己实施一个。但是,如果您已经排序了 int 数组,则可以使用 sort.searchints ,如下所示。

package main

import (
    "fmt"
    "sort"
)

func main() {
    fmt.println(sort.searchints([]int{2,3,4,5,9,10,11}, 5))
}

同样来自 godoc:

searchints 在排序的整数切片中搜索 x 并返回搜索指定的索引。如果 x 不存在(可能是 len(a)),则返回值是插入 x 的索引。切片必须按升序排序。

编写一个函数。下面的示例假设 indexof 返回数字的第一个索引,如果没有找到,则返回 -1。

// IndexOf returns the first index of needle in haystack
// or -1 if needle is not in haystack.
func IndexOf(haystack []int, needle int) int {
    for i, v := range haystack {
        if v == needle {
            return i
        }
    }
    return -1
}

Run this code on the Go Programming Language Playground

到这里,我们也就讲完了《相当于indexOf》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>