1

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

mappie
  • 482
  • 2
  • 12
  • Just want to point out, the function is named `get` because it's an operator function so you can use it like `str[4]`. If there are multiple parameters, `get` would be a terrible choice for a function name because the word is meaningless on its own. – Tenfour04 Jul 30 '20 at 14:54

3 Answers3

4
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() } )
IR42
  • 8,587
  • 2
  • 23
  • 34
1

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))
Shalu T D
  • 3,921
  • 2
  • 26
  • 37
  • Concatenating strings in a loop is [bad practice](https://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java), as it has to create a new (and progressively longer) String object each time round.  Far better to use an explicit [StringBuilder](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-string-builder/), or even better, call [buildString()](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/build-string.html). – gidds Jul 30 '20 at 19:49
0

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(""))
Kamal
  • 44
  • 6