【问题标题】:indexOf('?') for a list not workingindexOf('?') 列表不起作用
【发布时间】:2015-01-08 20:53:49
【问题描述】:

我必须返回列表中包含“?”字符的第一个元素的索引。

为什么它应该是 8 却显示为 -1。 indexOf 对字符不起作用吗?我应该使用 indexWhere 还是会有相同的结果?

scala> val lst = List("question?mark")
lst: List[String] = List(question?mark)

scala> lst.indexOf('?')
res2: Int = -1

当我将 val 设为字符串时,它可以正常工作

【问题讨论】:

    标签: list scala collections scala-collections indexof


    【解决方案1】:

    试试lst.indexWhere(_.contains("?"))

    indexOf "查找此列表中某个值第一次出现的索引。" link

    因此它会找到等于“?”的字符串在列表中。

    【讨论】:

    • 当我测试这是 scala 时,它会通过给出 -1 来理解不存在问号但它一直说 int = 0
    • "列表中包含?的第一个元素的索引" 0。实际上你的列表只包含一个元素。
    • @acolist,你能给你的测试用例列表项不包含“吗?”结果是0?
    【解决方案2】:

    .indexOf 作用于字符串

    scala> "where is ?".indexOf('?')
    res5: Int = 9
    

    所以试试

    lst(0).indexOf('?')
    

    对于你可以使用的列表中的每个元素

    scala> val lst = List("question?mark","where?","hello","why?")
    lst: List[String] = List(question?mark, where?, hello, why?)
    
    scala> lst.map(_.indexOf('?'))
    res4: List[Int] = List(8, 5, -1, 3)
    

    【讨论】:

    • 在这种情况下,您将找到所有包含“?”的元素,而不是第一个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 2013-04-17
    • 1970-01-01
    相关资源
    最近更新 更多