Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find last occurrence of a String in array using Kotlin

Tags:

kotlin

I have this array: ["cat", "dog", "lion", "tiger", "dog", "rabbit"]

  • How can I find the position of the first "dog"?

  • How can I find the position of last "dog"?

  • How can I throw an error when I search for something that is not in the array?

Currently I have a for loop but I am having difficulty with making it print the position.

like image 575
Edo Ambi Avatar asked Sep 10 '17 07:09

Edo Ambi


2 Answers

For your question of finding the first and last occurrences in an Array there is no need to use a for-loop at all in Kotlin, you can simply use indexOf and lastIndexOf

As for throwing an error you can throw an Exception if indexOf returns -1, observe:

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")
}

Output

[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
like image 103
Sash Sinha Avatar answered Dec 10 '22 16:12

Sash Sinha


@shash678 has given what a most useful answer, but more could be useful depending on more about the nature of your question.

Specifically: Are you seeking an answer to the exact problem stated, or looking to learn kotlin?

I have this array: ["cat", "dog", "lion", "tiger", "dog", "rabbit"]

But do you specifically need an Array? In kotlin, this case would normally be coded as a List, so

  val wordList = listOf("cat", "dog", "lion", "tiger", "dog", "rabbit")

The list is 'immutable' and generally List (or when needed MutableList) are used in Kotlin unless there are other reasons such as compatibility with existing code or in the case of MutableList, specific performance requirements.

Further, if your question is more "How do I solve this problem using a for loop with indexes?", then code like this:

val wordList = listOf("cat", "dog", "lion", "tiger", "dog", "rabbit")
fun List<String>.findWord( target:String):Pair<Int,Int>?{
    var (first,last) = Pair(-1,-1)
    for(idx in this.indices){
        if(this[idx]==target){
            last = idx
            if(first ==-1) first = idx
        }
    }
    return if(first>-1) Pair(first,last) else null
}
println("result ${wordList.findWord("dog")!!}")

Not at all the best way to solve the specific problem, but may be of use for anyone wondering "How to access index values within a for loop", rather than solve this specific problem. So this is an example of kotlin coding rather than a recommended solution to this problem.

The last part of the question was "How I throw an error when I search for something that is not in the array?".

The kotlin 'idiom' is to return null on failure and use the null safety to handle the error. This code simply raises an exception if null is returned. That is not very information, but using ?: throw MyException("Oops") in place of !! would allow a custom exception if a MyException class inheriting from Execption is declared.

like image 29
innov8 Avatar answered Dec 10 '22 14:12

innov8