Edo Ambi
Edo Ambi

Reputation: 81

Find last occurrence of a String in array using Kotlin

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

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

Upvotes: 6

Views: 6165

Answers (3)

Sash Sinha
Sash Sinha

Reputation: 22360

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

Upvotes: 8

innov8
innov8

Reputation: 2209

@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.

Upvotes: 1

Maraj Hussain
Maraj Hussain

Reputation: 1596

You can use method lastIndexOf for getting the last occurrence of a value & indexOf for getting the first occurrence of a value from array.below is the code.

 fun main(args: Array<String>) {
     // Declaring array
     val arr = arrayOf("cat", "dog", "lion", "tiger", "dog", "rabbit")
     // for getting the last position of item
     println(arr.lastIndexOf("dog"))
    // for getting the first index of item
     println(arr.indexOf("dog"))
 }

Upvotes: 0

Related Questions