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++
}
}
You can get the character at a particular index within a string, string buffer, or string builder by invoking the charAt accessor method. The index of the first character is 0; the index of the last is length()-1 .
To read a character in Java, we use next() method followed by charAt(0). The next() method returns the next token/ word in the input as a string and chatAt() method returns the first character in that string. We use the next() and charAt() method in the following way to read a character.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With