Iurii Manakov
Iurii Manakov

Reputation: 13

How to use the get method of Kotlin String

I know how to get only one character from a string:

val str = "Hello Kotlin Strings"
println(str.get(4)) //prints o

But how I can get several characters in one method println(str.get())

For example:

val str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
print(str.get(8,11,14,21,4,24,14,20)) //ERROR

How to get ILOVEYOU using only one println(str.get())?

Please any advice or a link to guide me. Thanks

Upvotes: 1

Views: 193

Answers (3)

Shalu T D
Shalu T D

Reputation: 4039

How I can get several characters in one method println(str.get())

Answer:

You can use below extension method of String:

fun String.get(vararg item: Int) : String {
    val builder = StringBuilder()
    item.forEach {
        builder.append(this[it])
    }
    return builder.toString()
}

As you said, you can use single string.get(8,11,14,21,4,24,14,20) method as below:

val str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
print(str.get(8,11,14,21,4,24,14,20))

Upvotes: 1

Kamal
Kamal

Reputation: 44

You would not be able to as each get() function only returns 1 character at the specified index. See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/get.html

You could either do a str.get() call for each specific letter, like this;

    val str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    val list = listOf(8,11,14,21,4,24,14,20)
    println(list.map { str.get(it) }.joinToString(""))

Upvotes: 0

IR42
IR42

Reputation: 9672

println( listOf(8,11,14,21,4,24,14,20).map { str[it] }.joinToString("") )
// or
println( listOf(8,11,14,21,4,24,14,20).joinToString("") { str[it].toString() } )

Upvotes: 4

Related Questions