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

旧城冷巷雨未停 提交于 2019-12-05 15:13:24

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)

Could you please try this method instead?

private fun abc(x: String) {
    $p = 1; 
    do {
        $p++
    }while (x[p]!= "+")
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!