scala - muliline string split

后端 未结 3 837
太阳男子
太阳男子 2020-12-12 03:10

I have this:

val msg = \"Preparado para cocinar...\"
val message = msg.splitAt(msg.length()/2)

println(message._1 + \"\\n\" + message._2.trim())
         


        
3条回答
  •  一生所求
    2020-12-12 03:35

    Another quite inelegant functional solution.

    I'm pretty sure something better will come given some thought

    Code

    def divide(msg: String): (String, String) = {
    
      //index each letter
      val indexed = msg.zipWithIndex
    
      //split at first blank space after midpoint    
      val (fst, snd) = indexed span {case (c, i) => i < indexed.size/2 || c != ' '}
    
      //utility to recompose indexed parts
      def unzipString(s: Seq[(Char, Int)]) = s.map(_._1).mkString.trim
    
      //get separated lines    
      (unzipString(fst), unzipString(snd))
    }
    

    REPL

    scala> val msg = "Parando para cocinar..."
    msg: String = Parando para cocinar...
    
    scala> val indexed = msg.zipWithIndex
    indexed: scala.collection.immutable.IndexedSeq[(Char, Int)] = Vector((P,0), (a,1), (r,2), (a,3), (n,4), (d,5), (o,6), ( ,7), (p,8), (a,9), (r,10), (a,11), ( ,
    12), (c,13), (o,14), (c,15), (i,16), (n,17), (a,18), (r,19), (.,20), (.,21), (.,22))
    
    scala> val (fst, snd) = indexed span {case (c, i) => i < indexed.size/2 || c != ' '}
    fst: scala.collection.immutable.IndexedSeq[(Char, Int)] = Vector((P,0), (a,1), (r,2), (a,3), (n,4), (d,5), (o,6), ( ,7), (p,8), (a,9), (r,10), (a,11))
    snd: scala.collection.immutable.IndexedSeq[(Char, Int)] = Vector(( ,12), (c,13), (o,14), (c,15), (i,16), (n,17), (a,18), (r,19), (.,20), (.,21), (.,22))
    
    scala> def unzipString(s: Seq[(Char, Int)]): String = s.map(_._1).mkString.trim
    unzipString: (s: Seq[(Char, Int)])String
    
    scala> (unzipString(fst), unzipString(snd))
    res2: (String, String) = (Parando para,cocinar...)
    

    Updated: the original answer had a couple of blatantly obvious errors

提交回复
热议问题