0

I am learning scala right now. When I wrote a statement as below,

"abcdpqrs".split("").grouped(2).map(_.mkString("")).mkString("|")

i expected it to print,

ab|cd|pq|rs

but instead it is printing,

a|bc|dp|qr|s

I find this behaviour erratic. Am I missing something or is there anything else which can partition the list as I expected?

Prasanna Sundar
  • 1,650
  • 1
  • 11
  • 16

1 Answers1

3

You're getting a|bc|dp|qr|s as a result because of split("")

scala> "abcdpqrs".split("")
res0: Array[String] = Array("", a, b, c, d, p, q, r, s)

If you do this without split("") you get

scala> "abcdpqrs".grouped(2).map(_.mkString("")).mkString("|")
res4: String = ab|cd|pq|rs

which I think is what you want

EDIT

For the record @marstran has helpfully pointed out that this only happens in java 7 - the behaviour of split was changed with java 8 and instead split("") will give

scala> "abcdpqrs".split("")
res0: Array[String] = Array(a, b, c, d, p, q, r, s)
Hamish
  • 1,015
  • 9
  • 20
  • no problem! I only know this because it's caught me out before! – Hamish Jan 08 '16 at 15:22
  • thanks anyway! I was breaking my head on this for past 30 mins! i'll accept your answer soon! – Prasanna Sundar Jan 08 '16 at 15:23
  • 1
    I'm not seeing this behavior at all. In my local scala shell (2.11.7 on Linux), running `"abcdpqrs".split("").grouped(2).map(_.mkString).mkString("|")` results in `res6: String = ab|cd|pq|rs`. Is there possibly something different in my shell than in yours? – bedwyr Jan 08 '16 at 15:24
  • I didn't try on my local machine, I was using hackerrank's shell. But the thing which is said above, solved my problem – Prasanna Sundar Jan 08 '16 at 15:25
  • @bedwyr that's really weird - I hope not, I'm just using the standard repl here? – Hamish Jan 08 '16 at 15:26
  • Wow, very interesting :) Also, when I use `split` on that string, I don't see the initial empty-string in the Array: `res3: Array[String] = Array(a, b, c, d, p, q, r, s)`. Will keep an eye out for this in the future. – bedwyr Jan 08 '16 at 15:28
  • 2
    The behaviour of the `split` method actually changed slightly in Java 8. When called with the empty string as a parameter, Java 7 will give return `Array("", a, b, c, d, p, q, r, s)`, while Java 8 will return `Array(a, b, c, d, p, q, r, s)`. – marstran Jan 08 '16 at 15:33
  • See http://stackoverflow.com/questions/22718744/why-in-java-8-split-sometimes-removes-empty-strings-at-start-of-result-array/27477312#27477312 – marstran Jan 08 '16 at 15:35
  • @marstran good knowledge!! Yes, I'm using java 7 on my work machine, so that solves that mystery! – Hamish Jan 08 '16 at 15:35