Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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++
    }
}
like image 911
Aakash Sharma Avatar asked May 11 '18 17:05

Aakash Sharma


People also ask

How do you find the index of a specific value in a string?

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 .

How do you read an individual character in a string in Java?

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.


1 Answers

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)
like image 141
mantono Avatar answered Sep 22 '22 09:09

mantono