1
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
    }

此代码段导致

java.lang.ArrayIndexOutOfBoundsException: -1

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

4

1 回答 1

3

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)
于 2019-05-04T17:52:57.770 回答