0

I need to split this string by a semicolon and write to the map with the key word and value number.

"Mercedes 2000; BMW 2500; Audi 2000; Porsche 1000"

Final output of map should looks like:

{Mercedes=2000, BMW=2500, Audi=2000, Porsche=1000}
rost
  • 367
  • 1
  • 2
  • 16

3 Answers3

3

First split by ";" and then map:

val str = "Mercedes 2000; BMW 2500; Audi 2000; Porsche 1000"
val map = str
        .split(";")
        .map { it.trim().substringBefore(" ") to it.trim().substringAfter(" ") }
        .toMap()
println(map)

will print:

{Mercedes=2000, BMW=2500, Audi=2000, Porsche=1000}
forpas
  • 117,400
  • 9
  • 23
  • 54
2
val input = "Mercedes 2000; BMW 2500; Audi 2000; Porsche 1000"

val map = HashMap<String, String>()
val keyValue = input.split("; ") // split the input into key-value items
for (item in keyValue) {
    val keyValueSplit = item.split(" ")// split the key and the value
    val key = keyValueSplit[0]
    val value = keyValueSplit[1]
    map[key] = value // insert into result map
}
println(map)

Output

{Audi=2000, Porsche=1000, Mercedes=2000, BMW=2500}

Be careful to do the first split at "; " with a whitespace. Otherwise the second split at the whitespace" " will give you a different result.

Simulant
  • 16,683
  • 7
  • 55
  • 85
1

As you have specifically asked for a regex solution:

val map = HashMap<String, String>()
val regex = """(\S+)\s+(\d+)(?:;\s+)?""".toRegex()
for (m in regex.findAll("Mercedes 2000; BMW 2500; Audi 2000; Porsche 1000"))
    map[m.groupValues[1]] = m.groupValues[2]
println(map)

This yields

{Audi=2000, Porsche=1000, Mercedes=2000, BMW=2500}

Read more about Regex in Kotlin here and see a demo on regex101.com.

Jan
  • 38,539
  • 8
  • 41
  • 69