kotlin - Kotlin-字 rune 字与预期的Int类型不一致

标签 kotlin type-inference

我正在为程序的类型而苦苦挣扎,我被要求首先在JS中进行操作,并且效果很好,但现在我无法实现结果。
您认为我应该提出另一个“算法”吗?在此先感谢您的宝贵时间。

fun main(){
    // the idea is to put numbers in a box
    // that cant be larger than 10
    val data = "12493419133"
    var result = data[0]
    var currentBox = Character.getNumericValue(data[0])
    var i = 1

    while(i < data.length){

        val currentArticle =  Character.getNumericValue(data[i])
         currentBox += currentArticle

        println(currentBox)

        if(currentBox <= 10){
            result += Character.getNumericValue(currentArticle)
        }else{
            result += '/'
            //var resultChar = result.toChar()
            // result += '/'
            currentBox = Character.getNumericValue(currentArticle)
            result += currentArticle
        }
        i++
    }
    print(result) //should print 124/9/341/91/33
}

最佳答案

结果实际上是Char类型,并且重载运算符函数+仅接受Int以增加ASCII值以获得新的Char。

public operator fun plus(other: Int): Char

以idomatic Kotlin方式,您可以解决您的问题:

fun main() {
    val data = "12493419133"

    var counter = 0
    val result = data.asSequence()
        .map(Character::getNumericValue)
        .map { c ->
            counter += c
            if (counter <= 10) c.toString() else "/$c".also{ counter = c }
        }
        .joinToString("")  // terminal operation, will trigger the map functions

    println(result)
}

编辑:如果data太大,则可能要使用StringBuilder,因为它不会在每次迭代字符时都创建字符串,并且可以使用list.fold()来代替自己的计数器

fun main() {
    val data = "12493419133"

    val sb = StringBuilder()
    data.fold(0) { acc, c ->
        val num = Character.getNumericValue(c)
        val count = num + acc
        val ret = if (count > 10) num.also { sb.append('/') } else count
        ret.also { sb.append(c) }  // `ret` returned to ^fold, next time will be passed as acc
    }

    println(sb.toString())
}

关于kotlin - Kotlin-字 rune 字与预期的Int类型不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62444911/

相关文章:

android - Jetpack 撰写 : Hoisitng click state from DropDownItems to DropDownMenu

android - 如何在 Kotlin 中使用 Retrofit 和 Observables 创建异步调用?

Kotlin 推断 JOOQ 方法错误

verilog - 如何在 Verilog 中推断 block RAM

reflection - 在 Kotlin 中对具有默认参数的函数使用 callBy 时出错

android - 在 Kotlin 中循环字符串并用新行替换句号

haskell - haskell中的函数组合类型推断

c++ - lambda 中的递归调用 (C++11)

c# - 使用接口(interface)和通用约束进行类型推断

scala - 为什么在 Scala 中使用存在类型时会忽略类型参数的边界?