1

Hi have a string and the if format of the string is mentioned below:

val str = "{a=10, b=20, c=30}"

All the parameters inside this string is unique and separated by comma and space. Also This string always starts with '{' and ends with '}'. I want to create a Map out of this string something like below:

val values = Map("a" -> 10, "b" -> 20, "c" -> 30)

What is the most efficient way I can achieve this?

4 Answers 4

4
scala> val str = "{a=10, b=20, c=30}"
str: String = {a=10, b=20, c=30}

scala> val P = """.*(\w+)=(\d+).*""".r
P: scala.util.matching.Regex = .*(\w+)=(\d+).*

scala> str.split(',').map{ case P(k, v) => (k, v.toInt) }.toMap
res2: scala.collection.immutable.Map[String,Int] = Map(a -> 10, b -> 20, c -> 30)
Sign up to request clarification or add additional context in comments.

Comments

1

Use regex can simply achieve this:

  "(\\w+)=(\\w+)".r.findAllIn("{a=10, b=20, c=30}").matchData.map(i => {
    (i.group(1), i.group(2))
  }).toMap

Comments

0

The function you want to write is pretty easy:

def convert(str : String) : Map[String, String] = {
    str.drop(1).dropRight(1).split(", ").map(_.split("=")).map(arr => arr(0)->arr(1)).toMap
}

with drop and dropRight, you remove the brackets. Then you split the String with the expression ,, which results in multiple Strings.

Than you split each of this strings, which results in arrays with two elements. Those are used to create a map.

Comments

0

I would do it likes this (I think regex is not needed here):

val str = "{a=10, b=20, c=30}"

val values: Map[String, Int] = str.drop(1).dropRight(1) // drop braces
  .split(",") // split into key-value pairs
  .map { pair =>
  val Array(k, v) = pair.split("=") // split key-value pair and parse to Int
  (k.trim -> v.toInt)
}.toMap

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.