how to split the text in scala line by line

text will be "asd_fgh_jklm" output : asd fgh jk lm if the last word is 4 then 2+2 if it is 3 then 2+1

Conditions:

Remove all _ characters in string

no.of chars>=4

Print each of 3 charcters in to new line.

If remaining no.of characters < =4

4 - 2+2

3- 2+1

2- 2

1 - 1

then split and print as 2 characters into one line, remaining into next line

1 answer

  • answered 2018-07-11 12:51 dyrkin

    I do not know what exactly you mean, but maybe this will help you:

    def magicSplit(str: String, separator: String) =
      str.split(separator).toList match {
        case init :+ last => init ++ last.grouped(2)
      }
    
    
    val res1 = magicSplit("asd_fgh_jklm", "_")
    val res2 = magicSplit("asd_fgh_jk", "_")
    val res3 = magicSplit("asd_fgh_j", "_")
    val res4 = magicSplit("asd_fgh_jkl", "_")
    

    results:

    res1: List[String] = List(asd, fgh, jk, lm)
    res2: List[String] = List(asd, fgh, jk)
    res3: List[String] = List(asd, fgh, j)
    res4: List[String] = List(asd, fgh, jk, l)