Home > Enterprise >  Array index in kotlin
Array index in kotlin

Time:11-13

Let's say i have an array that contains the names of the fruit and i want to take it out if write the first letter. I confuse because i don't what the keyword when i got this kind of question.

fun main() {
var char = readline()
val name = arrayOf("Apple", "Banana", "Cherry", "Dragonfruit")
}

When i type "a", the result is apple and so on.

I can't use

Thank you for helping me. I just learn about kotlin.

CodePudding user response:

Something like this should work:

fun main() {
    val char = readLine()
    val name = arrayOf("Apple", "Banana", "Cherry", "Dragonfruit")

    val filteredNames = name
         .filter { word -> word.startsWith(char.orEmpty(), ignoreCase = true) }
    System.out.println(filteredNames)
}

Given your description, it seems to me that we should not be case-sensitive while checking and hence the ignoreCase = true as a parameter in startsWith() method.

CodePudding user response:

You can filter the array based on the input character:

fun main() {
    val char = readLine()
    val names = arrayOf("Apple", "Banana", "Cherry", "Dragonfruit")

    val filteredNames = names.filter { 
         it.startsWith(char.orEmpty(), true) 
    }
}

For clarification:

  • it refers to the current element being iterated.

  • The function startsWith() receives a string used for comparison as the first parameter, and a boolean indicating if the evaluation should ignorecase or not.

  • since readline() is an optional string (String?) type, char can be null. To avoid a NullPointerException being thrown upon comparison inside startsWith(), you use the method .orEmpty(), which is a nicer way to write it.startsWith(char ?: "", true).

If instead of all elements starting with a character, you only want the first one, you can call first() on the array:

fun main() {
    val char = readLine()
    val names = arrayOf(
        "Apple", 
        "Albatroz", 
        "Anaconda", 
        "Banana", 
        "Cherry", 
        "Dragonfruit"
    )

    val firstElementStartingWithChar = names
        .first { 
             it.startsWith(char.orEmpty(), true) 
        }
}

If you choose to type the letter a as an input, firstElementStartingWithChar will only contain "Apple".

  • Related