簡體   English   中英

Kotlin 將字符串拆分為范圍

[英]Kotlin split string into range

我需要從字符串中獲取一個范圍。 ; - 是一個分隔符。

因此,例如,我有字符串“10;15;1”,我需要得到從 10 到 15 的范圍(忽略最后一個數字)。

預期結果:

“10;15;1”-> 10..15

所以我試着寫這段代碼。 我怎樣才能改善它? 它看起來很糟糕而且很無用

val arr = "10;15;1".split(";").dropLast(1).map { it.toBigDecimal() }
val someRange = arr[0] .. arr[1]

如果你不關心驗證,你可以這樣做:

fun toRange(str: String): IntRange = str
    .split(";")
    .let { (a, b) -> a.toInt()..b.toInt() }

fun main() {
    println(toRange("10;15;1"))
}

Output:

10..15

如果你想更加偏執:

fun toRange(str: String): IntRange {
    val split = str.split(";")
    require(split.size >= 2) { "str must contain two integers separated by ;" }

    val (a, b) = split

    return try {
        a.toInt()..b.toInt()
    } catch (e: NumberFormatException) {
        throw IllegalArgumentException("str values '$a' and/or '$b' are not integers", e)
    }
}

fun main() {
    try { println(toRange("oops")) } catch (e: IllegalArgumentException) { println(e.message) }
    try { println(toRange("foo;bar;baz")) } catch (e: IllegalArgumentException) { println(e.message) }
    println(toRange("10;15;1"))
}

Output:

str must contain two integers separated by ;
str values 'foo' and/or 'bar' are not integers
10..15

function 非常具體,因此它不能存在於標准庫中。 盡管我可以建議使用正則表達式的替代方法並在字符串格式不正確的情況下返回 null 值,但我並不反對該實現。 但它使用正則表達式。

fun rangeFrom(str: String) : ClosedRange<BigDecimal>? {
    val regex = """^(\d+);(\d+);\d+$""".toRegex()
    val result = regex.find(str)
    return result?.destructured?.let { (fst, snd) ->
        fst.toBigDecimal() .. snd.toBigDecimal()
    }
}

或者您可以更新您的 function 檢查split生成的列表的長度是否>= 2並直接使用arr[0].toBigDecimal().. arr[1].toBigDecimal但它並沒有太大的不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM