How can I access a char in string in at specific number?
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)
The beauty of Kotlin is that you can do it in few ways, eg.
You can simply access it by index:
while (x[i] != '+') { i++ }
Converting to
CharArray
val chars: CharArray = x.toCharArray() while (chars[i] != '+') { i++ }
You can also use idiomatic Kotlin (preferred):
forEach
x.forEach { c -> if (c == '+') return@forEach }
forEachIndexed if you care about index
x.forEachIndexed { index, c -> if (c == '+') { println("index=$index") return@forEachIndexed } }
In both cases, your character is accessed with c