问题
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 charAt() method.
private fun abc(x: String) {
var i: Int = 0
while (x[i].toString() != "+") {
var y: Char = x[i]
i++
}
}
回答1:
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)
回答2:
Could you please try this method instead?
private fun abc(x: String) {
$p = 1;
do {
$p++
}while (x[p]!= "+")
}
回答3:
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
来源:https://stackoverflow.com/questions/50297288/how-can-i-access-a-char-in-string-in-at-specific-number