我有一個字串,我想根據 & 和 = 拆分它
kit=xxxx&accountType=xxxxx&accountId=1234
我想要 accountId 并且它的值是 1234。我嘗試了下面的方法,覺得它有更多的時間復雜性。
你能提出更好的方法嗎?
myString = "kit=xxxx&accountType=xxxxx&accountId=1234"
val queryComponents: List<String>? = myString?.split("&")?.map { it }
queryComponents?.forEach { element ->
if (element.contains(key)) {
val search = element.split("=").map { it }
print("key = " search[0] "value = " search[1])
}
}
uj5u.com熱心網友回復:
您的方法很好,但是您的代碼很難閱讀。我們可以先拆分&,然后拆分,=這可能是最容易理解的:
val accountId = myString.splitToSequence('&')
.map { it.split('=') }
.find { it[0] == "accountId" }
?.get(1)
或者我們可以只拆分一次,然后=使用字串工具進行搜索。這可能會快一點,因為我們不創建額外的字串串列:
val accountId = myString.splitToSequence('&')
.find { it.startsWith("accountId=") }
?.takeLastWhile { it != '=' }
請注意,通過使用splitToSequence()we split by&直到我們找到accountId=。然后我們結束回圈。
根本不拆分并只在字串中搜索&accountId=. 或者使用正則運算式。它需要考慮多種情??況:accountId=在開頭、結尾或中間。
無論如何,我相信所有這些解決方案都具有完全相同的時間復雜度O(n).
uj5u.com熱心網友回復:
val myString = "kit=xxxx&accountType=xxxxx&accountId=1234"
val components = myString
.split("&", "=", ignoreCase = true)
.chunked(2) { it[0] to it[1] }
.toMap()
println(components["accountId"])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/392954.html
