2

Suppose this String: Point(123 456).

What would be an efficient and clean way to extract and assign 123 and 456 (as String) to a Tuple2 at once?

What I did:

val str = "Point(123 456)"
val tab = str.stripPrefix("Point(").stripSuffix(")").split("\\s")
val tuple2 = (tab(0), tab(1))
println(tuple2)  // displays the (123,456)

Pretty ugly ...

2 Answers 2

5

The most straightforward way is using a regex extractor. These are quite fast, actually, for simple stuff like this--as fast as your solution. Is it prettier? I don't know.

val p = """Point\((\d+)\s(\d+)\)""".r
"Point(123 456)" match { case p(a,b) => (a,b) }

On my machine, extracting 10,000 such pairs takes 3.90 ms using this method, and 4.35 ms using yours (mostly due to the extra slowness of split).

If you need it to be faster yet for some odd reason,

def uuple2(s: String) = {
  if (!s.startsWith("Point(") || s(s.length-1) != ')') throw new Exception
  val i = s.indexOf(' ',6)
  if (i < 0 || i+2 >= s.length) throw new Exception
  (s.substring(6,i), s.substring(i+1,s.length-1))
}

This is way faster: 0.38 ms for 10k on my machine.

Sign up to request clarification or add additional context in comments.

Comments

4

You could use a regex:

val str = "Point(123 456)"
val re = """Point\((\d+) (\d+)\)""".r

val re(f, s) = str
println((f, s))

1 Comment

I was trying this (regexp) at this time :) Indeed, I think it's the better solution for this case. Thanks :)

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.