【问题标题】:Index out of bounds exception with indexofindexof 的索引超出范围异常
【发布时间】:2019-05-04 17:40:36
【问题描述】:
def toLowerCase(str: String): String = {
        val lowerCase = "abcdefghijklmnopqrstuvwxyz".split("")
        val upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")
        var returnStr = ""

        str.split("").foreach(c => if (lowerCase.contains(c)) returnStr += c 
                else returnStr += lowerCase(upperCase.indexOf(c)))

        returnStr
    }

这段代码sn-p导致

java.lang.ArrayIndexOutOfBoundsException: -1

不确定在这种情况下什么会导致传递 -1 的索引

【问题讨论】:

  • 注意 java.lang.String.toLowerCase([Locale]) 已经完成了您尝试做的所有工作,更高效、更可靠,并且还可以处理非拉丁字母。
  • 我知道,这是提示实现 toLowerCase() 函数的解决方案

标签: java arrays scala indexing


【解决方案1】:

indexOf 可以返回-1str 不仅可以包含拉丁字母)。

  /** Finds index of first occurrence of some value in this $coll.
   *
   *  @param   elem   the element value to search for.
   *  @tparam  B      the type of the element `elem`.
   *  @return  the index of the first element of this $coll that is equal (as determined by `==`)
   *           to `elem`, or `-1`, if none exists.
   *
   *  @usecase def indexOf(elem: A): Int
   *    @inheritdoc
   *
   *    $mayNotTerminateInf
   *
   */
  def indexOf[B >: A](elem: B): Int = indexOf(elem, 0)

【讨论】:

    猜你喜欢
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2011-12-25
    • 2023-04-10
    相关资源
    最近更新 更多