How can I access a char in string in at specific number?

Aakash Sharma picture Aakash Sharma · May 11, 2018 · Viewed 19.5k times · Source

I tried this code but it is giving me errors. So how can I access a character in a string in kotlin? In java, it can be done by the charAt() method.

private fun abc(x: String) {
    var i: Int = 0
    while (x[i].toString() != "+") {
        var y: Char = x[i]
        i++
    }
}

Answer

mantono picture mantono · May 11, 2018

The equivalent of Javas String.charAt() in Kotlin is String.get(). Since this is implemented as an operator, you can use [index] instead of get(index). For example

val firstChar: Char = "foo"[0]

or if you prefer

val someString: String = "bar"
val firstChar: Char = someString.get(0)