【问题标题】:Kotlin split string into rangeKotlin 将字符串拆分为范围
【发布时间】:2021-05-26 20:10:16
【问题描述】:

我需要从字符串中获取一个范围。 ; - 是一个分隔符。

所以,例如,我有字符串“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]

【问题讨论】:

  • 鉴于非常具体的要求,我根本不会说这是糟糕的代码。您可能考虑的更改包括查看是否可以对输入格式做出更少的假设;并更好地处理无效输入。此外,如果数字总是整数,那么Int 可能比BigDecimal 更简单。这看起来太具体了,不值得拆分成一个单独的函数,除非你能以某种方式使其更通用。
  • 我可能建议的唯一方法是不要使用 lambda,而是使用 map(String::toBigDecimal),这样代码在不失其简洁性的情况下更加自我记录。

标签: arrays string kotlin parsing range


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    该函数非常具体,因此它不能存在于标准库中。尽管我可以建议使用正则表达式的替代方法并在字符串格式不正确的情况下返回空值,但我并不反对该实现。但它使用正则表达式。

    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 生成的列表长度为&gt;= 2 并直接使用arr[0].toBigDecimal() .. arr[1].toBigDecimal,但差别不大。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      相关资源
      最近更新 更多