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++
}
}
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)