使用Kotlin查找数组中最后一次出现的String

Edo*_*mbi 4 kotlin

我有这个数组: ["cat", "dog", "lion", "tiger", "dog", "rabbit"]

  • 我怎样才能找到位置的的第一个 "狗"?

  • 我怎样才能找到位置最后一个 "狗"?

  • 当我搜索不在数组中的内容时,如何抛出错误

目前我有一个for循环,但我很难打印位置.

sha*_*678 8

对于在数组中查找第一次最后一次出现的问题,在Kotlin中根本不需要使用for循环,只需使用indexOflastIndexOf

至于抛出错误,如果indexOf返回则可以抛出异常,观察:-1

import java.util.Arrays

fun main(args: Array<String>) {
  // Declaring array
  val wordArray = arrayOf("cat", "dog", "lion", "tiger", "dog", "rabbit")

  // Declaring search word
  var searchWord = "dog"

  // Finding position of first occurence
  var firstOccurence  = wordArray.indexOf(searchWord)

  // Finding position of last occurence
  var lastOccurence = wordArray.lastIndexOf(searchWord)

  println(Arrays.toString(wordArray))

  println("\"$searchWord\" first occurs at index $firstOccurence of the array")

  println("\"$searchWord\" last occurs at index $lastOccurence of the array")

  // Testing something that does not occur in the array
  searchWord = "bear"
  var index = wordArray.indexOf(searchWord)
  if (index == -1) throw Exception("Error: \"$searchWord\" does not occur in the array")
}
Run Code Online (Sandbox Code Playgroud)

产量

[cat, dog, lion, tiger, dog, rabbit]
"dog" first occurs at index 1 of the array
"dog" last occurs at index 4 of the array
java.lang.Exception: Error: "bear" does not occur in the array
Run Code Online (Sandbox Code Playgroud)