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]

该函数非常特殊,标准库中一定不存在。尽管我可以建议使用 Regex 的替代方案并在字符串格式不正确时返回空值,但我并不反对该实现。但它使用正则表达式。

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()
    }
}

或者您可以只更新您的函数,检查由 split 生成的列表的长度是否为 >= 2 并直接使用 arr[0].toBigDecimal() .. arr[1].toBigDecimal,但差别不大。

如果您不关心验证,您可以这样做:

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

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

输出:

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"))
}

输出:

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