如何从文本 kotlin 中检索特定字符串?
How to retrieve particular string from a text kotlin?
我得到的扫描结果是一个类似 ---
的字符串
DriverId=60cb1daa20056c0c92ebe457,金额=10.0
我想从此字符串中检索驱动程序 ID 和数量。
我怎样才能取回?
请帮忙...
这是我能想到的可能方式之一。
val driverID= str.substringAfter("DriverId=", "").substringBefore(",", "")
val amount = str.substringAfter("Amount=", "")
这取决于你的整体格式。如果你真的有这种固定格式,@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()
我得到的扫描结果是一个类似 ---
的字符串DriverId=60cb1daa20056c0c92ebe457,金额=10.0
我想从此字符串中检索驱动程序 ID 和数量。 我怎样才能取回? 请帮忙...
这是我能想到的可能方式之一。
val driverID= str.substringAfter("DriverId=", "").substringBefore(",", "")
val amount = str.substringAfter("Amount=", "")
这取决于你的整体格式。如果你真的有这种固定格式,@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()