22

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++
    }
}
peterh
  • 11,875
  • 18
  • 85
  • 108
Aakash Sharma
  • 427
  • 1
  • 6
  • 15

3 Answers3

60

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)
mantono
  • 873
  • 1
  • 10
  • 8
1

Could you please try this method instead?

private fun abc(x: String) {
    $p = 1; 
    do {
        $p++
    }while (x[p]!= "+")
}
Naren Murali
  • 19,250
  • 3
  • 27
  • 54
1

The beauty of Kotlin is that you can do it in few ways, eg.

  1. You can simply access it by index:

    while (x[i] != '+') {
        i++
    }
    
  2. Converting to CharArray

    val chars: CharArray = x.toCharArray()
    
    while (chars[i] != '+') {
        i++
    }
    
  3. 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

Melquiades
  • 8,496
  • 1
  • 31
  • 46