Home > Back-end >  Split a string twice in Kotlin
Split a string twice in Kotlin

Time:12-26

I have a string and I want to split it based on the & and =

kit=xxxx&accountType=xxxxx&accountId=1234

I want accountId and it's value 1234 out of it. I have tried the below approach and feel it has more time complexity.

Could you please suggest better approach?

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

CodePudding user response:

Your approach is fine, but your code is pretty hard to read. We can split by & first and then by = which is probably the easiest to understand:

val accountId = myString.splitToSequence('&')
    .map { it.split('=') }
    .find { it[0] == "accountId" }
    ?.get(1)

Or we can split only once and then search for = using string utils. This could be a little faster as we don't create additional lists of strings:

val accountId = myString.splitToSequence('&')
    .find { it.startsWith("accountId=") }
    ?.takeLastWhile { it != '=' }

Note that by using splitToSequence() we split by & only until we find accountId=. Then we end the loop.

It could be even faster to not split at all and just search the string for &accountId=. Or use regular expressions. It would require to take into account multiple cases: accountId= is at the beginning, at the end or in the middle.

Anyway, I believe all these solutions have exactly the same time complexity of O(n).

CodePudding user response:

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"])
  • Related