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

你说的曾经没有我的故事 提交于 2019-12-22 08:19:49

问题


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.

  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



来源:https://stackoverflow.com/questions/50297288/how-can-i-access-a-char-in-string-in-at-specific-number

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