【问题标题】:How to retrieve particular string from a text kotlin?如何从文本 kotlin 中检索特定字符串?
【发布时间】:2021-09-04 23:20:37
【问题描述】:

我正在以字符串形式获取扫描结果,例如 ---

DriverId=60cb1daa20056c0c92ebe457,Amount=10.0

我想从此字符串中检索驱动程序 ID 和数量。 我该如何找回? 请帮忙...

【问题讨论】:

    标签: string kotlin text getvalue


    【解决方案1】:

    这取决于您的整体格式。 @iLoveYou3000 建议的子字符串等基本操作如果你真的有这种固定格式,就可以正常工作。

    如果密钥是动态的,或者将来可能会更改,您还可以使用更通用的方法,例如使用split()

    val attributeStrings = input.split(",")
    val attributesMap = attributeStrings.map { it.split("=") }.associate { it[0] to it[1] }
    
    val driverId = attributesMap["DriverId"]
    val amount = attributesMap["Amount"].toDouble() // or .toBigDecimal()
    

    【讨论】:

    【解决方案2】:

    这是我能想到的可能方式之一。

    val driverID= str.substringAfter("DriverId=", "").substringBefore(",", "")
    val amount = str.substringAfter("Amount=", "")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-16
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      相关资源
      最近更新 更多